【发布时间】:2016-04-29 16:15:51
【问题描述】:
我想从 PHP 调用 Python 3 脚本(带参数)并处理返回的信息。
//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
问题是这个问题在 Stack Overflow 上被问过很多次了,每一个都有不同的答案:
执行函数(here 和 here)
$output = array();
exec("python hi.py", $output);
var_dump( $output);
转义shell函数(here)
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
shell执行函数(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)));
系统函数(here)
$mystring = system('python myscript.py myargs', $retval);
所有这些答案都被接受并获得了相当多的赞成票。如果有的话,哪一种是从 PHP 调用 Python 脚本的正确方法?
【问题讨论】:
-
这 4 个函数基本上都是一样的。您可以比较 php.net 上的功能并使用最适合您需要的功能。
标签: php python-3.x