Running a python script within wordpress

I have a WordPress install for a personal blog and I’m gradually porting all of the little web bits I have written over the years to pages on the blog.

One such page is http://www.projecttoomanycooks.co.uk/cgi-bin/memory/majorAnalysis.py which is a simple python script that returns a list of words – I’d like to embedd that behavior within a wordpress page – could someone point me in the right direction for the easyist way of running a spot of python within wordpress?

EDIT – following the wonderful answer below, I have got a lot futher… but unfortunately still not quite there…

I have python that executes on server…

projecttoomanycooks server [~/public_html/joereddington/wp-content/plugins]#./hello.py 
Hello World!

and it’s in the same directory as the activated plugin…

The python code… which has the following code…

#!/usr/bin/python
print("Hello World!")

The php:

<?php
/**
 * Plugin Name: Joe's python thing.
 * Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
 * Description: A brief description of the Plugin.
 * Version: The Plugin's Version Number, e.g.: 1.0
 * Author: Name Of The Plugin Author
 * Author URI: http://URI_Of_The_Plugin_Author
 * License: A "Slug" license name e.g. GPL2
 */
/*from http://wordpress.stackexchange.com/questions/120259/running-a-python-scri
pt-within-wordpress/120261?noredirect=1#120261  */
add_shortcode( 'python', 'embed_python' );

function embed_python( $attributes )
{
    $data = shortcode_atts(
        array(
            'file' => 'hello.py'
        ),
        $attributes
    );
    $handle = popen( __DIR__ . "https://wordpress.stackexchange.com/" . $data['file'], 'r');
    $read   = fread($handle, 2096);
    pclose($handle);

    return $read;
}

3

You can use popen() to read or write to a Python script (this works with any other language too). If you need interaction (passing variables) use proc_open().

A simple example to print Hello World! in a WordPress plugin

Create the plugin, register a shortcode:

<?php # -*- coding: utf-8 -*-
/* Plugin Name: Python embedded */

add_shortcode( 'python', 'embed_python' );

function embed_python( $attributes )
{
    $data = shortcode_atts(
        [
            'file' => 'hello.py'
        ],
        $attributes
    );

    $handle = popen( __DIR__ . "https://wordpress.stackexchange.com/" . $data['file'], 'r' );
    $read = '';

    while ( ! feof( $handle ) )
    {
        $read .= fread( $handle, 2096 );
    }

    pclose( $handle );

    return $read;
}

Now you can use that shortcode in the post editor with [python] or [python file="filename.py"].

Put the Python scripts you want to use into the same directory as the plugin file. You can also put them into a directory and adjust the path in the shortcode handler.

Now create a complex Python script like this:

print("Hello World!")

And that’s all. Use the shortcode, and get this output:

enter image description here

Leave a Comment