Running a python script within wordpress

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