gpt4 book ai didi

php - 响应在 PHP 命令行上运行的程序提出的问题

转载 作者:可可西里 更新时间:2023-11-01 13:31:46 25 4
gpt4 key购买 nike

我想知道如何与在命令行 PHP 脚本中运行的程序进行交互。场景是:

  1. 开始执行程序。
  2. 阅读输出直到提出问题(我猜是通过阅读 STDOUT)。
  3. 键入答案并按 Enter(我猜是通过写入 STDIN)。用户无需输入此内容,脚本通过读取和解释步骤 2 的输出已经知道要回答什么。
  4. 再次阅读输出,直到提出新问题。
  5. 再次输入答案并按 Enter。同样,脚本知道一切,无需用户输入。
  6. 此问答场景重复 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 写入文件)。

最佳答案

您当然是在正确的轨道上。

最好从代码中的明显问题开始:

while ($buffer = fgets($pipes[1])) {
echo $buffer;
}

这个循环永远不会退出。在某个时候程序会问你一个问题,但此时你的代码仍在执行(阻塞的)fgets 调用。

至于如何编写正常工作的代码......

最明显的解决方案是在提供答案之前不要费心等待提示。这将有效,只要:

  1. 您不需要根据程序的先前输出调整您的响应

  2. 程序正在从它的标准输入中读取并且不会在任何时候清除缓冲区

事实上,您甚至不需要对此进行控制:

program <input.txt >output.txt 2>errors.txt

但假设 1 和/或 2 不适用,并且假设它已经在重定向其标准输出(这表明故事的内容比我们所知的更多),那么,

...
if (is_resource($process)) {
while ($buffer=fgets($pipes[2]) { // returns false at EOF/program termination
if (strpos($buffer, 'STEP 1:') !== false) {
fwrite($pipes[0], "My first answer\n");
} else if (strpos($buffer, 'STEP 2:') !== false) {
fwrite($pipes[0], "My second answer\n"); //enter the answer
}
}
}

在请求/响应周期中执行乱序问题检查和分支作为练习留给读者。

关于php - 响应在 PHP 命令行上运行的程序提出的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com