我遇到了一个问题:对于一个在命令行中100%工作的python脚本,使用shell\u exec(),或PHP中的exec()来获得一致的结果(有时我得到python脚本的输出,有时我没有)。我的猜测(未经证实)是由于某种原因,php没有在关闭进程之前等待python脚本的结果,但我不确定。你知道吗
注意我使用的是nginx/php5 fpm(不是apache)
更新我还加入了一个健全性检查,确实有效
#sanity.py
import sys
sanity = sys.argv[1]
print "You are totally " + sanity
echo shell_exec(escapeshellcmd("/usr/bin/python sanity.py sane"));
我用PHP编写了以下代码,用于调用运行python脚本的命令。。。你知道吗
$command = escapeshellcmd("/usr/bin/python app.py $var1 $var2")
session_write_close();
shell_exec($command);
python脚本是(非常简化的)
import sys
var1 = sys.argv[1]
var2 = sys.argv[2:]
print some_function(var1,var2)
现在。。。当我从命令行运行这个命令时,如下所示。。。你知道吗
python app.py 1234 asdf
我得到的结果没有任何问题。然而,PHP代码有时只返回一个结果(没有任何真正的原因来解释为什么有时才返回)。你知道吗
另外,我编写了以下代码作为替代选项,得到了类似或相同的结果。。。有时有效,有时一无所获。。。你知道吗
$command = escapeshellcmd("/usr/bin/python /var/app/" . $command);
$pipes = array();
$descriptors = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w"),
);
session_write_close();
$process = proc_open($command, $descriptors, $pipes) or die("Can't open process $command!");
$output = "";
while (!feof($pipes[2])) {
$read = array($pipes[2]);
stream_select($read, $write = NULL, $except = NULL, 0);
if (!empty($read)) {
$output .= fgets($pipes[2]);
}
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $output;
有没有一种方法可以解决到底发生了什么,或者解决这个问题,使它始终工作?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐