【问题标题】:How to run python script and compare the output inside php如何运行python脚本并比较php中的输出
【发布时间】:2014-01-18 15:33:22
【问题描述】:

我有一个运行 python 脚本的 php 脚本。我必须将 python 脚本的输出与 php 脚本中的特定常量进行比较。 我尝试使用 exec 和 popen。这是我到目前为止尝试过的代码

$out=NULL;
$pid=exec("python /home/krishna/online/createProblems.py $contest $pcode $fn1 $fn2",$out) or die("error");
if ($out=="1"){echo "Successfully inserted problem";}

并使用 popen

$pid=popen("python /home/krishna/online/createProblems.py $contest $pcode $fn1 $fn2","r") or die("error");
$ot=fread($pid,256);
if ($ot=="1"){echo "Successfully inserted problem";}

两个代码都不能正常工作...... 当我测试输出时,我得到“1”作为输出。但与“1”比较是行不通的。

【问题讨论】:

    标签: php python exec popen


    【解决方案1】:

    您可以将管道用于标准输入、标准输出和标准错误。

    function get_output($cmd) {
        $descriptorspec = array(0 => array('pipe', 'r'),     // stdin
                                1 => array('pipe', 'w'),     // stdout
                                2 => array('pipe', 'w'));    // stderr
    
        $process = proc_open($cmd, $descriptorspec, $pipes);
        $output = '';
        if (is_resource($process)) {
            fwrite($pipes[0], 'some std input can be here');    // not necessary
            fclose($pipes[0]);
    
            $output = stream_get_contents($pipes[1]);
            $err = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);
    
            proc_close($process);
    
            if (!empty($err)) {
                throw new Exception();
            }
        }
        return $output;
    }
    

    现在您应该传递需要执行的 $cmd。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-06
      • 2021-07-13
      • 2020-05-16
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 2014-03-23
      相关资源
      最近更新 更多