简体   繁体   English

如何从PHP正确调用Python 3脚本?

[英]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. 我想从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

The problem is this has been asked many times on Stack Overflow, and there are different answers each one: 问题是,在Stack Overflow上已经问了很多遍了,每个答案都有不同:

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 ) Shell执行功能( 此处

// 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? 从PHP调用Python脚本的正确方法是哪一种(如果有)?

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. 我经常使用shell_exec,因为它对我来说更容易调试,因为我要做的只是在<pre>标签中打印出一个字符串。 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. 使用: 2>&1位于脚本末尾和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. 这还允许您查看错误输出,这很有可能需要弄清楚为什么它在命令行中起作用,但是从PHP运行它时却不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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