dongluoheng3324
2014-01-18 15:33
浏览 50
已采纳

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

I have a php script that runs a python script. I have to compare python script's output with specific constants in php script. I tried using exec and popen. Here is the code I tried so far

$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";}

and using 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";}

Both codes are not working properly.... When I tested outputs I got "1" as output. but comparing with "1" is not working.

图片转代码服务由CSDN问答提供 功能建议

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

  $ out = NULL; 
 $ pid = exec(“python /home/krishna/online/createProblems.py $ contest $ pcode  $ fn1 $ fn2“,$ out)或死(”错误“); 
if($ out ==”1“){echo”成功插入问题“;} 
   
 \  n 

并使用popen

  $ pid = popen(“python /home/krishna/online/createProblems.py $ contest $ pcode $ fn1 $ fn2”,“r  “)或死(”错误“); 
 $ ot = fread($ pid,256); 
if($ ot ==”1“){echo”成功插入问题“;} 
  <  / pre> 
 
 

两个代码都无法正常工作.... 当我测试输出时,我得到“1”作为输出。 但与“1”相比并不起作用。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanliaozhi2915 2014-01-18 15:39
    最佳回答

    You can use pipes for stdin, stdout and 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;
    }
    

    Now you should pass the needed $cmd to be executed.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题