Run a Python Program from PHP



In PHP, the 'exec()' or 'shell_exec' function can be used. It can be executed via the shell and the result can be returned as a string. It returns an error if NULL is passed from the command line or returns no output at all.

'exec()' Function

The exec function is used for executing commands in the shell and command line of an external program and optinally capture the last line of the output.

Syntax

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

'shell_exec()' Function

The shell_exec is similiar to exec but it captures and return the entire output of the the command as a string, instead of just the last line.

Syntax

shell_exec(string $command);

To Run a Python program from PHP

The process include few steps as follows.

  • Preparing Python script

  • Preparing PHP Script

  • Setting Permission

  • Running the PHP script from (command line or web server)

Prepare Python Script

The below code line refers, to python script

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

Prepare PHP Script

As a next step create a PHP script which execute the Python program using 'exec' or 'shell_exec' function.

< ?php
// To 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;
? >

Setting Permissions

Make sure that the PHP has permission to execute the Python program and to access any required files or directories.

chmod +x /path/to/test.py

Running the PHP from Web Server

Placing the PHP script into web server's document root. Now through a web browser we can access the PHP script

http://localhost/test.php

Running from the Command line

We can the PHP script from both web server or by Command line.

php /path/to/test.php

Output

Hello from Python!
Updated on: 2024-09-10T16:38:20+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements