[英]How to properly call Python 3 script from PHP?
我想从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上已经问了很多遍了,每个答案都有不同:
$output = array();
exec("python hi.py", $output);
var_dump( $output);
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
// 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)));
$mystring = system('python myscript.py myargs', $retval);
所有这些答案都是可以接受的,并且具有不错的投票数。 从PHP调用Python脚本的正确方法是哪一种(如果有)?
他们都做同样的事情,但是输出却不同。 我建议使用最适合您的情况的一种。
我经常使用shell_exec,因为它对我来说更容易调试,因为我要做的只是在<pre>
标签中打印出一个字符串。 人们往往会忘记一件事,尤其是当他们尝试调试东西时。 使用: 2>&1
位于脚本末尾和args)。 拿上面的例子之一,它看起来像这样:
shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)) . " 2>&1");
这还允许您查看错误输出,这很有可能需要弄清楚为什么它在命令行中起作用,但是从PHP运行它时却不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.