我有一个简单的C++程序,我试图通过python脚本执行。 (我对编写脚本非常陌生),而且我无法通过管道读取输出。从我所看到的,看起来像readline()在没有EOF的情况下无法工作,但我希望能够在程序中间读取并让脚本响应输出的内容。而不是读输出,它只是挂起 的Python脚本:子进程readline挂起等待EOF
#!/usr/bin/env python
import subprocess
def callRandomNumber():
print "Running the random guesser"
rng=subprocess.Popen("./randomNumber", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
i=50
rng.stdin.write("%d\n" % i)
output=rng.stdout.readline()
output=rng.stdout.readline()
callRandomNumber()
和C++文件,其产生一个与100之间的随机数,然后检查用户猜测直至他们猜测正确
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
cout<<"This program generates a random number from 1 to 100 and asks the user to enter guesses until they succuessfully guess the number. It then tells the user how many guesses it took them"<<endl;
srand(time(NULL));
int num=rand()%100;
int guessCount=0;
int guess=-1;
cout<<"Please enter a number: ";
cin>>guess;
while(guess!=num){
if(guess>num){cout<<"That guess is too high. Please guess again: ";}
else{cout<<"That guess is too low. Please guess again: ";}
cin>>guess;
guessCount++;
}
cout<<"Congratulations! You solved it in "<<guessCount<<" guesses!"<<endl;
return 0;
}
最终的目标是让脚本用二进制搜索来解决问题,但现在我只是希望能够在不读取文件末尾的情况下读取一行文件
是的,但我希望能够使脚本现有的方案,而不是修改方案,以适应脚本 –
没有通用的方法以“解决”EOF问题。否则,你怎么知道这条线实际上已经结束?如果你知道该程序,不要阅读直到换行,只需阅读你需要的字符的确切数量。否则,使其返回一个换行符。你的另一种选择是使用超时,这非常糟糕。 –
你不需要阅读确切的金额。 [只要几乎同步就足够了](http://stackoverflow.com/a/23795689/4279)(OS管道缓冲区提供容限)。 – jfs