Python in WordPress – A “Hello World” implementation

I tried it step by step and finally succeeded.

Step 1 – hello.py

I tried to create the hello.py file with Atom on Windows 10 and uploaded it to a Linux server for many times. It could run with the “python3 hello.py” command, but always failed to run when using the “./hello.py” command.

I had to create it on the Linux server and the “./hello.py” command worked.

# pwd
/var/www/html/wordpress/wp-content/plugins/run-python
# cat hello.py 
#!/usr/bin/env python3
print("Hello")
# chmod +x hello.py
# ./hello.py 
Hello

Step 2 – t-popen.py

I created the t-popen.py file with Atom on Windows 10 and uploaded it to the Linux server. This PHP file was used to make sure the popen() function worked.

# cat t-popen.php 
<?php

/* Add redirection so we can get stderr. */
$handle = popen( __DIR__ . '/hello.py', 'r' );
$read   = '';

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

pclose( $handle );

var_dump( $read );
echo $read;
# php t-popen.php 
string(6) "Hello
"
Hello

Step 3 – The WP plugin

I created the run-python.php file with Atom on Windows 10 and uploaded it to the Linux server.

<?php
/**
 * Try - Run Python
 *
 * @package     Try\Run Python
 *
 * Plugin Name: Try - Run Python
 * Plugin URI:
 * Description: Try to run a Python script in the WordPress plugin.
 * Version:     1.0
 * Author:      Box
 * Author URI:
 */

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   = '';

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

    pclose( $handle );

    return $read;
}

Step 4

I activated the plugin and tried to add a shortcode as [python] to a post.

The “hello” string showed in the content when I viewed the post.

Note

The 3 files mentioned above are all located in the same directory which is “/var/www/html/wordpress/wp-content/plugins/run-python” in this case.