Run a Python program from PHP

In PHP, you can execute Python scripts using built-in functions like exec() or shell_exec(). These functions allow you to run Python programs via the shell and capture their output.

exec() Function

The exec() function executes commands in the shell and optionally captures the output. It returns only the last line of output by default.

Syntax

exec(string $command, array &$output = null, int &$return_var = null);

shell_exec() Function

The shell_exec() function is similar to exec() but captures and returns the entire output of the command as a string, instead of just the last line.

Syntax

shell_exec(string $command);

Running a Python Program from PHP

The process involves the following steps −

  • Preparing the Python script
  • Creating the PHP script
  • Setting proper permissions
  • Executing the PHP script

Prepare Python Script

First, create a simple Python script that we want to execute −

# test.py
print("Hello from Python!")

Prepare PHP Script

Create a PHP script that executes the Python program using shell_exec() function −

<?php
// Run the Python program 
$command = escapeshellcmd('python3 /path/to/test.py');

// Use shell_exec to execute the command and capture the output
$output = shell_exec($command);

// Display the output
echo $output;
?>

Using exec() Function

Alternatively, you can use the exec() function to run Python scripts −

<?php
$command = escapeshellcmd('python3 /path/to/test.py');
exec($command, $output, $return_var);

// Display the output
foreach ($output as $line) {
    echo $line . "\n";
}
?>

Setting Permissions

Make sure that PHP has permission to execute the Python script and access required files or directories.
chmod +x /path/to/test.py

Running from Command Line

You can execute the PHP script from the command line −

php /path/to/test.php
Hello from Python!

Conclusion

Use shell_exec() when you need the complete output as a string, or exec() when you want line-by-line output control. Always use escapeshellcmd() to sanitize commands for security.

Updated on: 2026-03-15T08:31:49+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements