Diepakk Patel Full Stack Passionate Developer

Diepakk Patel

Diepakk Patel

How to call Python file from within PHP?

December 29, 2020, by admin, category PHP

In Linux you need to do two things
1) make python file executable

sudo chmod +x testd.py

2) make sure you defined the environment where python is getting executed

#!usr/bin/<path of python env>

3) use escapeshellcommand() to include python file and shell_exec() to execute it. You can pass command line arguments also as params

In PHP use shell_exec function:

To call a Python file from within a PHP file in Linux server, using the shell_exec function.

For example

<?php
    $command = escapeshellcmd('/usr/custom/testd.py');
    $output = shell_exec($command);
    echo $output;
?>

In your script on the top, we need to specify the interpreter as well. So in py file, add the following line at the top or on First Line:

#!/usr/bin/env python

Another way you can also provide the interpreter when executing the command.

For example

<?php
    $command = escapeshellcmd('python2 /usr/custom/testd.py');
    $output = shell_exec($command);
    echo $output;
?>

Another way – Also using passthru and handling the output buffer directly:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 

So, what do you think ?