How to Run a Python Script on a PHP/HTML File

Linux TLDR
Last Updated:
Reading time: 5 minutes

In this article, you will learn how to run a Python script on a PHP (or even a plain HTML) file using two different methods, along with practical examples.

I assume you have already installed Python with Pip and set up the web development environment on your Linux system, with the web root directory located at β€œ/var/www/htmlβ€œ, and that you have the necessary root or sudo permissions.

πŸ“
If you are a Windows user, your web root directory depends on the tool you used to set up web development, such as XAMPP, WampServer, etc.

Before we continue, it’s important to note that running Python scripts with GUI operations like Matplotlib or Tkinter requires external tools, while CLI programs like NumPy or Pandas can run using built-in functions.

Keeping all of this in mind, let’s learn how to run a Python script in a PHP or HTML file on your Linux system.

Practice Python File for Demonstration

In this example, I’ll use two different Python scripts: one is a basic script that outputs β€œHello from Linux TLDRβ€œ, and the other is a slightly more complex file that utilizes NumPy for complex mathematical operations.

Python Script 1: Displaying a simple β€œHello from Linux TLDR” output

def main():
    print("Hello from Linux TLDR")

if __name__ == "__main__":
    main()

Python Script 2: Performing complex mathematical operations using the NumPy library

πŸ“
The following Python script requires NumPy to be installed on your Linux system. If you haven’t already, use the β€œpip install numpy” command to initiate the installation.
import numpy as np

# Create a NumPy array from a list
my_list = [1, 2, 3, 4, 5]
numpy_array = np.array(my_list)

# Print the NumPy array
print("NumPy Array:")
print(numpy_array)

# Basic operations with NumPy arrays
print("\nBasic Operations:")
print("Sum:", np.sum(numpy_array))
print("Mean:", np.mean(numpy_array))
print("Standard Deviation:", np.std(numpy_array))

# Create a 2D NumPy array
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Print the 2D NumPy array
print("\n2D NumPy Array:")
print(matrix)

# Transpose the 2D NumPy array
transposed_matrix = np.transpose(matrix)

# Print the transposed 2D NumPy array
print("\nTransposed 2D NumPy Array:")
print(transposed_matrix)

I suggest you use the above Python script for demonstration purposes, copy its content, and save it in the β€œ/var/www/html” directory with the file names β€œpy_script1.py” and β€œpy_script2.py” for the first and second Python script, respectively.

Here is how your directory structure would look with the output of both Python scripts.

web root directory with python script

So, let’s start with the first method to run a Python script on PHP without using any external tools.

Method 1: Run Python Scripts on PHP File Without External Tools

Begin by creating a PHP file in the β€œ/var/www/html” web root directory with the name β€œindex.php” and pasting the following PHP code into it:

<?php
$pythonScript = "py_script1.py";
exec("python3 $pythonScript", $output, $returnCode);

if ($returnCode === 0) {
    echo implode("\n", $output);
} else {
    echo "Error running Python script. Return code: $returnCode";
}
?>

In the above program, we first execute the β€œpy_script1.py” file, and do not forget to replace the β€œpython3” command with the one you use to initiate the Python interpreter on your Linux system.

When accessing the β€œindex.php” page from your browser via β€œlocalhost/index.php” or your IP address, you will get the following Python script output:

running python script using php

Likewise, you can replace β€œpy_script1.py” with β€œpy_script2.py” in the previously mentioned PHP script to execute the Python script containing NumPy code and then refresh the page.

running python script with numpy code using php

The result lacks formatting due to encapsulation before printing, but it functions as intended. Unfortunately, this method doesn’t support running Python scripts with GUI operations.

Now, if we discuss the code used in the Python script, it includes some PHP variables, the β€œexec()” function, and an if-else statement.

Most things are self-explanatory; the most important one is the β€œexec()” function, which is used to execute a command via the shell and returns the last line of the command’s output.

It enables the execution of external programs or shell commands, commonly used for running system commands, executing scripts, or performing similar tasks on the server where PHP is operating.

But remember to use it cautiously, as this function will execute the script on your Linux system, granting all permissions and enabling system modifications.

Method 2: Run Python Script on an HTML File Using PyScript

This method can help you achieve the same task in your HTML file using the PyScript framework, which allows any HTML file to run Python scripts.

With PyScript in your HTML file, you can also run a Python script performing GUI operations like Matplotlib, Altair, Folium, etc., and further, you can write Python code in your HTML file.

The only complaint I have with this tool is that it launches an integrated terminal within the web page, displays the output of the Python script in the terminal, and downloads the necessary components each time you refresh the page.

But for now, let’s set this aside and explore how you can use PyScript to execute Python scripts or code in your HTML file.

I assume you have at least a little knowledge of HTML, so create a basic HTML template and add the following PyScript CDN in the head tag.

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>

Next, each library that your Python script or code requires should be included under the β€œ<py-config>” tag within the β€œpackages” variable in an array.

Your Python code should be written under the β€œ<py-script>” tag. If you are importing an external Python script from your system, use the β€œsrc” attribute to specify the path of the Python script.

In my case, I will directly run the β€œpy_script2.py” file, importing the NumPy library, so my HTML file will look like the one below.

<html>
        <head>
                <!-- PyScript CDN -->
                <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
                <script defer src="https://pyscript.net/latest/pyscript.js"></script>
        </head>
        <body>
                <!-- Greeting from Linux TLDR -->
                <div style="text-align: center">
                <h1>Running Python Script/Code in your HTML file</h1>
                <p>Thanks for following <a href="https://linuxtldr.com">Linux TLDR</a></p>
                <div>
                <!-- Importing supporting libraries for require Python Script/Code -->
                <py-config>
                        packages = ["numpy"]
                </py-config>
                <!-- Your Python Script/Code -->
                <py-script src="py_script2.py">
                </py-script>
        </body>
</html>

If you are following along with me, you can copy the HTML code above, save it in an β€œindex.html” file within your β€œ/var/www/html” directory, and then navigate to β€œlocalhost/index.html” in your web browser to access it.

running python script in html file

In this way, you can execute any Python script or write Python code in your HTML file using the PyScript framework. The only limitation is that you cannot interact with Python as you would with PHP, and the output is displayed in the terminal.

If you are creating a β€œTry it Out” editor or showcasing the functionality of any Python script on your web page, this could be a great solution.

If you’d like to dig deeper into this framework, be sure to visit its documentation page or head directly to the examples page if you have a basic understanding of HTML and JavaScript.

Final Word

There’s nothing left to say since most questions are already answered in the article, but if you have any, feel free to let us know in the comment section.

Till then, peace!

Join The Conversation

Users are always welcome to leave comments about the articles, whether they are questions, comments, constructive criticism, old information, or notices of typos. Please keep in mind that all comments are moderated according to our comment policy.

2 thoughts on β€œHow to Run a Python Script on a PHP/HTML File”

  1. Bro, you saved me a lot of time! BTW, PyScript is inconvenient at the beginning but works great after reading a little documentation.

    Reply