1

I have the following code to run a Python script from PHP and pass inputs values to stdin. (source)

$descriptorspec = array(
        0 => array("pipe", "r"), 
        1 => array("pipe", "w")
    );  
    $process = proc_open('python script.py', $descriptorspec, $pipes, null, null); 
    if (is_resource($process)) {
        fwrite($pipes[0], "first input"); // input 1            
        fwrite($pipes[0], "second input"); // input 2

        fclose($pipes[0]); // has to be closed before reading output!
        fgets($pipes[1]); 
        $output = "";
        while (!feof($pipes[1])) {
            $output .= fgets($pipes[1]) . "</br>";
        }
        fclose($pipes[1]);
        proc_close($process);  
        echo $output;
    }

Problem: $output captures everything except the first line of stdout on the command line. For example, if the Python program prints Hello, from, Python is successive lines, $output only contains from and Python. How do I capture the first line of stdout too?

Community
  • 1
  • 1
raul
  • 1,209
  • 7
  • 20
  • 36
  • 3
    What do you think `fgets($pipes[1]); ` in line 11 does? – tkausl Aug 20 '16 at 05:15
  • Wow! I had used `fgets($pipes[1]);` in line 11 to avoid reading the initial prompts for input into `$output'. Turns out that contained the first line of the actual output as well. Thanks! – raul Aug 20 '16 at 13:20

0 Answers0