简体   繁体   中英

How to properly call Python 3 script from PHP?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM