Вопрос

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.

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top