How to call Python file from within PHP?

In PHP, you can execute Python scripts using built-in functions like shell_exec(), exec(), or proc_open(). Each method offers different levels of control over the process.

Using shell_exec()

The simplest approach − runs a command via the shell and returns the output as a string. Use escapeshellcmd() to sanitize the command ?

<?php
    $command = escapeshellcmd('/usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>
The square of 4 is 16

Specifying the Python Interpreter

If the script lacks a shebang line (#!/usr/bin/env python3), explicitly call the interpreter ?

<?php
    $command = escapeshellcmd('python3 /usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>
The square of 5 is 25

Using proc_open() for Complex Interactions

For sending input to the Python script or reading output/errors in real time, use proc_open() which provides control over stdin, stdout, and stderr ?

<?php
    $descriptorspec = [
        0 => ["pipe", "r"],  // stdin
        1 => ["pipe", "w"],  // stdout
        2 => ["pipe", "w"]   // stderr
    ];

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

    if (is_resource($process)) {
        fwrite($pipes[0], "6\n");
        fclose($pipes[0]);

        $output = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        $errors = stream_get_contents($pipes[2]);
        fclose($pipes[2]);

        proc_close($process);

        echo "Output: " . $output;
        if ($errors) {
            echo "Errors: " . $errors;
        }
    }
?>
Output: The square of 6 is 36

Comparison

Method Returns Output Send Input Error Handling
shell_exec() Yes (string) No No
exec() Yes (array + return code) No Return code only
proc_open() Yes (pipes) Yes (stdin pipe) Yes (stderr pipe)

Conclusion

Use shell_exec() for simple one-way execution, specify the interpreter explicitly when the script lacks a shebang, and use proc_open() when you need to send input or capture errors. Always sanitize commands with escapeshellcmd() to prevent shell injection.

Updated on: 2026-03-15T07:14:13+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements