【发布时间】:2016-03-06 08:04:30
【问题描述】:
我想知道如何与在命令行 PHP 脚本中运行的程序进行交互。场景是:
- 开始执行程序。
- 阅读输出,直到有人提出问题(我猜是通过阅读 STDOUT)。
- 输入答案并按 Enter(我猜是写到 STDIN)。用户不要输入这个,脚本已经通过阅读和解释步骤 2 的输出知道要回答什么。
- 再次阅读输出,直到提出新问题。
- 再次输入答案并按 Enter。同样,脚本知道这一切,不会发生用户输入。
- 此问答场景重复 x 次,直到程序完成。
如何编写一个 PHP 脚本来执行此操作?我在想我可能想使用proc_open(),但我不知道怎么用。我想它会是这样的,但它当然不起作用:
$descriptorspec = array(
0 => array('pipe', 'r'), //STDIN
1 => array('pipe', 'w'), //STDOUT
2 => array('pipe', 'r'), //STDERR
);
$process = proc_open('mycommand', $descriptorspec, $pipes, null, null);
if (is_resource($process)) {
// Get output until first question is asked
while ($buffer = fgets($pipes[1])) {
echo $buffer;
}
if (strpos($buffer, 'STEP 1:') !== false) {
fwrite($pipes[0], "My first answer\n"); //enter the answer
} else {
die('Unexpected last line before question');
}
// Get output until second question is asked
while ($buffer = fgets($pipes[1])) {
echo $buffer;
}
if (strpos($buffer, 'STEP 2:') !== false) {
fwrite($pipes[0], "My second answer\n"); //enter the answer
} else {
die('Unexpected last line before question');
}
// ...and so we continue...
} else {
echo 'Not a resource';
}
更新:我发现程序将问题输出到 STDERR(因为它将 STDOUT 写入文件)。
【问题讨论】:
-
@jsxqf 您没有阅读我的问题。这与我与 PHP 交互无关。这是关于 PHP 与另一个程序交互(没有我的任何输入)。
-
您的外部程序是否在“STEP 1:”和“STEP 2:”之后以及预期响应之前立即输出换行符(“\n”)?另外,问题总是相同且顺序相同吗?
-
我认为套接字将是同样的好选择?
-
你在什么操作系统上运行代码?
标签: php command-line-interface execution