Want to run python script in 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()
.
Create the plugin, register a shortcode:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?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__ . '/' . $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.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.