Call Python File from Within PHP



In PHP, we can execute Python scripts using built-in functions such as shell_exec(), exec() or popen() by enabling seamless integration between the two languages. Below are three methods to run a Python script from PHP with examples and explanations of each -

Using 'shell_exec()' function

One way to execute a Python script is by using the shell_exec function. This function runs a command via the shell and returns the output as a string. This function ensures that the command is safe to run by escaping any characters that could be harmful. The output of this script is sent back to the web page.

Example

In the following example, we are using the escapeshellcmd() function by ensuring that the command is safe to run by escaping any characters that could be harmful. The output of this script is reflected on the web page.

<?php
    // Specify the command to run the Python script located at '/usr/custom/test.py'
    $command = escapeshellcmd('/usr/custom/test.py');
    // Execute the command and capture the output
    $output = shell_exec($command);
    // Display the output
    echo $output;
?>

When the PHP script executes test.py with 4 as an argument, then the Python script calculates and prints the square of 4 as the output -

The square of 4 is 16

Specifying the Interpreter

Another method to call Python files from within PHP is to specify the Python interpreter directly in your PHP script. Instead of just calling the script, we explicitly call python3 followed by the path to the script. This is useful if the script does not have the proper shebang line.

Example

The following example shows a straightforward way to execute a Python script by specifying the interpreter -

<?php  
    // Prepare command to execute the Python script with an interpreter  
    $command = escapeshellcmd('python3 /usr/custom/test.py');  
    // Execute the command and capture the output  
    $output = shell_exec($command);  
    // Display the output  
    echo $output;  
?>

If you run this code, the output will be as follows -

The square of 5 is 25

Using 'proc_open()' Function

For more complex interactions, such as sending inputs to the Python script or reading outputs in real time, we can use proc_open(). This function provides greater control over the process.

Example

In the following example, the proc_open() opens a process and allows interaction. We specify how we want to handle standard input (stdin), output (stdout), and error output (stderr) -

<?php  
    // Command to execute the Python script  
    $descriptorspec = [  
        0 => ["pipe", "r"],  // stdin is a pipe that the child will read from  
        1 => ["pipe", "w"],  // stdout is a pipe that the child will write to  
        2 => ["pipe", "w"]   // stderr is a pipe that the child will write to  
    ];  

    // Process to open  
    $process = proc_open('python3 /usr/custom/test.py', $descriptorspec, $pipes);  

    if (is_resource($process)) {  
        // Write to the input pipe (stdin)  
        fwrite($pipes[0], "Some input\n");  
        fclose($pipes[0]);  

        // Read output from the output pipe (stdout)  
        $output = stream_get_contents($pipes[1]);  
        fclose($pipes[1]);  

        // Read any errors from the error pipe (stderr)  
        $errors = stream_get_contents($pipes[2]);  
        fclose($pipes[2]);  

        // Close the process  
        proc_close($process);  

        // Display the output and errors  
        echo "Output: " . $output;  
        if ($errors) {  
            echo "Errors: " . $errors;  
        }  
    }  
?>

In this method, we send the number 6 as input to the Python script's stdin. The script processes the input and returns the square of 6 as output -

The square of 6 is 36
Updated on: 2025-04-17T16:49:51+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements