How to call Python file from within PHP?

PythonServer Side ProgrammingProgrammingPHP

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

For example

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

This will call the script. But in your script at the top, you'll need to specify the interpreter as well. So in your py file, add the following line at the top:

#!/usr/bin/env python

Alternatively you can also provide the interpreter when executing the command.

For example

<?php
    $command = escapeshellcmd('python3 /usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>
raja
Published on 26-Dec-2017 17:12:15
Advertisements