从PHP shell_exec

时间:2017-08-17 20:30:57

标签: php python command-line exec shell-exec

我遇到一个问题是获得一致的结果(有时我得到python脚本的输出,有时我没有)在PHP中使用shell_exec()或exec()来获得工作100的python脚本命令行中的%时间。我的猜测(未经证实)是因为某些原因,php在关闭进程之前没有等待python脚本的结果,但我不确定。

注意我正在使用nginx / php5-fpm(不是apache)

更新我也会进行健全检查, DOES 工作

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

有没有办法解决到底发生了什么,或解决这个问题,以便它能够始终如一地运作?

0 个答案:

没有答案