2

I have a Python script that prompts the user for inputs.

input = raw_input("Enter input file: ")
model = raw_input("Enter model file: ")

While I can use the following PHP command to execute the script, how can I provide inputs when prompted?

$output = shell_exec("python script.py");

Also, like shell_exec(), I want to return all lines of output, not just the first/last line printed.

Solution that worked:

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

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

Reference: Piping between processes in PHP

raul
  • 1,209
  • 7
  • 20
  • 36

1 Answers1

0

I propose to concatenate all output lines with a delimiter character like $ and decompose it on the PHP side using explode function to have an array.

s.abbaasi
  • 952
  • 6
  • 14