如何运行python脚本并比较php内部的输出

2024-10-04 01:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个运行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

^{pr2}$

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


Tags: 代码py脚本homeoutpidnullonline
1条回答
网友
1楼 · 发布于 2024-10-04 01:33:11

可以对stdin、stdout和stderr使用管道。在

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。在

相关问题 更多 >