2

I would like to call a Python 3 script (with arguments) from PHP and process the returned information.

//server.php
arg1 = $_POST['arg1'];
arg2 = $_POST['arg2'];
args = array(arg1,arg2);

//pseudo code - THIS IS WHERE MY QUESTION IS
//$results = call_python3_script_somehow

echo $results

#script.py
import MyProcess

#take in args somehow

args = [arg1,arg2]
result = MyProcess(args)

return result

The problem is this has been asked many times on Stack Overflow, and there are different answers each one:

The execute function (here and here)

$output = array();
exec("python hi.py", $output);
var_dump( $output);

The escape shell function (here)

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

The shell execute function (here)

// This is the data you want to pass to Python
$data = array('as', 'df', 'gh');

// Execute the python script with the JSON data
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));

The system function (here)

$mystring = system('python myscript.py myargs', $retval);

All of these answers are accepted and have a decent number of upvotes. Which, if any of these, is the proper way to call a Python script from PHP?

Community
  • 1
  • 1
user1717828
  • 7,122
  • 8
  • 34
  • 59
  • Basically everyone of these 4 function does the same. You can compare the functions on php.net and use whichever fits your needs the most. – Charlotte Dunois Jan 22 '16 at 22:55

1 Answers1

3

They all do the same thing but have some different output. I would suggest to use the one that best fits your scenario.

I often use shell_exec because it's easier for me on debugging since I all I need to do is just print a string out in <pre> tags. There's one thing that people tend to forget, especially when they are trying to debug stuff. Use: 2>&1 at the end of the script and the args. Taking one of the examples you have above, it would look something like this:

shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)) . " 2>&1");

This allows you to view error output as well, which is more than likely what you'll need to figure out why it's working on the command line, but it's not working when you run it from PHP.

Paul Carlton
  • 2,785
  • 2
  • 24
  • 42