PHP执行Python脚本:在提示下提供输入,读取多个输出


PHP execute Python script: provide input on prompt, read multiple outputs

我有一个Python脚本,它会提示用户输入。

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

虽然我可以使用以下PHP命令来执行脚本,但如何在提示时提供输入?

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

此外,与shell_exec()一样,我希望返回所有输出行,而不仅仅是打印的第一行/最后一行。

有效的解决方案:

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

参考:PHP 中进程之间的管道

我建议用$这样的delimiter字符连接所有输出行,并在PHP端使用explode函数将其分解为一个数组。