的命令行上運行的程序提出的問題我想知道如何與我在命令行PHP腳本中運行的程序進行交互。該方案是:回答在PHP
- 啓動執行程序。
- 閱讀輸出,直到提問(通過閱讀標準輸出,我猜)。
- 鍵入答案,然後按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(因爲它寫到標準輸出到文件) 。
檢查了這一點:https://stackoverflow.com/questions/2929629/how-do-i-write-a-command-line-interactive-php-script – jsxqf
@jsxqf你沒有看過我的問題。這不關於我與PHP交互。這是關於PHP與另一個程序交互(沒有任何來自我的輸入)。 – TheStoryCoder
您的外部程序是否在「步驟1:」和「步驟2:」之後立即輸出換行符(「\ n」),然後再等待響應?另外,這些問題是否始終相同並且順序相同? –