isotropic-2022
Share
Blog
Search
Menu

How To Run Python Scripts in WordPress

By James LePage
 on July 24, 2023

How To Run Python Scripts in WordPress

By James LePage
 on July 24, 2023

Python continues to grow in popularity due to it's ease of use, powerful libraries, and simple syntax. I often find myself prototyping individual functionalities for WordPress with Python before converting them into PHP.

But instead of doing that, why not just run Python on WordPress? In this post, we'll discuss the various methods that can be used to run Python code directly on a WordPress website.

Run Python Scripts On WordPress

We can use a built in PHP function called exec()to run external scripts, including from Python. This will require a bit of code in both PHP and Python to get working, but it's quite easy once you understand how everything fits together.

david-clode-ojlt2xbwuws-unsplash-1

We can either create a plugin, or a code snippet. It depends on what you're looking to build, but I typically create a code snippet which is easier to manage on the frontend of the website.

First, make sure Python is globally installed on your server. You can do it yourself if you have root access, if not, you'll need to ask your webhost to install it. For example, on Cloudways, we needed to have them install Python for us.

PHP Function

We'll create the code to make a PHP function that will run any Python script in WordPress. For ease of use, I'll first show you a snippet that can be used with a Code Snippet Management plugin. Then we can take a look at building a custom plugin to do the same thing.

With this function, all of the Python scripts live in the media library, and we can select the script to run by specifying the media library item ID. Keep in mind, you'll probably need to allow the Python mime type to be uploaded. I used this plugin to enable it.

This looks a bit complicated because I ended up adding a lot of error handling. But at its core, all the code does is find the file from the media library, and run the script, outputting whatever it ends up returning.

πŸ“

Please note that I've used 'python3' as that's what's installed on my machine. You may want to change it to 'python'.

<?php function cwpai_run_python_script($media_id) { // Get the media file path on the server $media_path = get_attached_file($media_id); // Check if the media file exists if ($media_path) { // Set the Python command $python_command = 'python3 ' . escapeshellarg($media_path); // Run the Python script and capture the output exec($python_command, $output, $return_status); if ($return_status === 0) { // Script executed successfully, return the output return implode("\n", $output); } else { // Script execution failed, log the error and return an error message error_log('Error executing Python script. Command: ' . $python_command); return 'Error executing Python script.'; } } else { // Media file not found, log the error and return an error message error_log('Media file not found for media ID ' . $media_id); return 'Media file not found.'; } } // Usage example with media ID 6 $result = cwpai_run_python_script(6); // Output the result or handle the error if (is_string($result)) { // If the result is a string, it indicates an error message echo $result; } else { // If the result is not a string, it should be the output of the Python script // Display the output or perform further processing if needed echo $result; }

If we create a plugin, the structure may look like this:

wp-content/plugins/
    cwpai_my-python-plugin/
        cwpai_plugin.php
        assets/
            py/
                script.py

cwpai_plugin.php looks like this:

<?php /* Plugin Name: CWPAI My Python Plugin Description: A plugin to execute Python scripts for media files. Version: 1.0 Author: Your Name */ // Plugin code will go here. function cwpai_run_python_script($file_name) { // Get the plugin directory path $plugin_dir = plugin_dir_path(__FILE__); // Set the Python script path relative to the plugin directory $python_script_path = $plugin_dir . 'assets/py/' . $file_name; // Check if the Python script file exists if (file_exists($python_script_path)) { // Set the Python command $python_command = 'python3 ' . escapeshellarg($python_script_path); // Run the Python script and capture the output exec($python_command, $output, $return_status); if ($return_status === 0) { // Script executed successfully, return the output return implode("\n", $output); } else { // Script execution failed, log the error and return an error message error_log('Error executing Python script. Command: ' . $python_command); return 'Error executing Python script.'; } } else { // Python script file not found, log the error and return an error message error_log('Python script file not found: ' . $python_script_path); return 'Python script file not found.'; } }

For the plugin, it's quicker to include the Python Scripts in a specific directory (in this example, it's assets/py), allowing you to add and edit them over FTP. Therefore, its better if you have a lot of Python to run in WordPress.

To use it, simply call the function:

// Usage example with the file name "example.py" $result = cwpai_run_python_script('example.py'); // Output the result or handle the error if (is_string($result)) { // If the result is a string, it indicates an error message echo $result; } else { // If the result is not a string, it should be the output of the Python script // Display the output or perform further processing if needed echo $result; }

Shortcode

In "production" making a WP shortcode to run a Python script may also be helpful. We can use the same general function from above, modifying to to make it into a WordPress shortcode:

function cwpai_run_python_script($atts) { // Extract shortcode attributes $args = shortcode_atts(array('media_id' => '1'), $atts); // Get the media file path on the server $media_path = get_attached_file($args['media_id']); // Check if the media file exists if ($media_path) { // Set the Python command $python_command = 'python3 ' . escapeshellarg($media_path); // Run the Python script and capture the output exec($python_command, $output, $return_status); if ($return_status === 0) { // Script executed successfully, return the output return implode("\n", $output); } else { // Script execution failed, log the error and return an error message error_log('Error executing Python script. Command: ' . $python_command); return 'Error executing Python script.'; } } else { // Media file not found, log the error and return an error message error_log('Media file not found for media ID ' . $args['media_id']); return 'Media file not found.'; } } add_shortcode('run_python_script', 'cwpai_run_python_script');

Now you can use the shortcode [run_python_script media_id="6"] directly in your posts and pages. Replace "6" with the ID of the media file you want to use.

Use a Hosted Service

There are dozens of hosted services out there which allow you to access Python via APIs. This might be helpful for more complex projects and workflows, especially as you can access the output in PHP (using CURL) just as if you created your own custom plugin.

First, you'll need to create an API with Python. Here's a good resource for that. You'll essentially use Flask to make a webapp that exposes API endpoints. Then, you'll host that webapp with one of these services and access the different API endpoints with PHP.

Here's an example Python App that has the API:

# api.py import random from flask import Flask, request, jsonify app = Flask(__name__) things_list = [ "Apple", "Banana", "Carrot", "Dog", "Elephant", "Flower", "Guitar", "House", "Igloo", "Jacket" ] @app.route('/api/data', methods=['POST']) def process_data(): data = request.get_json() message = data.get('message') random_thing = random.choice(things_list) response_data = {'response': f'Received message: {message}. Random thing: {random_thing}'} return jsonify(response_data) if __name__ == '__main__': app.run(debug=True)

And how I'd access it in PHP, allowing me to use that data in WordPress (be it changing database fields, adding a new user, etc...)

<?php // API endpoint URL $apiUrl = 'http://your-python-api-domain.com/api/data'; // Data to send to the Python API $data = array( 'message' => 'Hello from PHP!' ); // Convert data to JSON $dataJson = json_encode($data); // Initialize cURL session $ch = curl_init(); // Set cURL options curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL session and capture the response $response = curl_exec($ch);

Now, with the $response data, you can use it with any WordPress functions. This is a basic example, but good to show how you'd do this.

If you're a bit technical and want something cheap, I'd suggest deploying your Python app using Digital Ocean which costs $2.50/mo for simple things.

If you want something quick, simple and easy, check out PythonAnywhere.com which starts at $5/mo.

Other than small scenarios, this method is probably the best way to do things.

Convert The Python Into PHP

Another option would be to simply convert the Python into PHP and use a plugin like Code Snippets to run that function.

You can manually convert it to PHP, or use a tool like ChatGPT or CodeWP to paste in the Python, and request it to be rewritten into PHP. Here's an example with CodeWP, an AI tool specifically built for WordPress creators:

lepage-2023-07-24-at-12-45-16

Conclusion

Being a WordPress developer who works with AI, I often find myself needing to quickly mock something up with Python, or even create complete production-level functionalities in the language.

By following these methods, you can quickly run python on a WordPress site and access whatever output it may produce.

Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Article By
James LePage
Contributors/Editors
notloggedin
James LePage is the founder of Isotropic, a WordPress education company and digital agency. He is also the founder of CodeWP.ai, a venture backed startup bringing AI to WordPress creators.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram