簡體   English   中英

如何從PHP正確調用Python 3腳本?

[英]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;

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)));

系統功能( 此處

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM