【发布时间】:2011-12-15 09:08:58
【问题描述】:
我有一个简单的 c++ 程序,我试图通过 python 脚本来执行它。 (我对编写脚本非常陌生)并且我无法通过管道读取输出。从我所看到的情况来看,如果没有 EOF,readline() 似乎将无法工作,但我希望能够在程序中间读取并让脚本响应输出的内容。而不是读取输出,它只是挂起 python脚本:
#!/usr/bin/env python
import subprocess
def call_random_number():
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()
call_random_number()
和 c++ 文件,它生成一个介于 1 到 100 之间的随机数,然后检查用户的猜测,直到他们猜对为止
#include<iostream>
#include<cstdlib>
int main(){
std::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\n";
std::srand(std::time(NULL));
int num = std::rand() % 100;
int guessCount = 0;
int guess = -1;
std::cout << "Please enter a number: ";
std::cin >> guess;
while(guess != num){
if (guess > num){
std::cout << "That guess is too high. Please guess again: ";
} else {
std::cout << "That guess is too low. Please guess again: ";
}
std::cin >> guess;
guessCount++;
}
std::cout << "Congratulations! You solved it in " << guessCount << " guesses!\n";
}
最终目标是让脚本通过二进制搜索解决问题,但现在我只想能够读取一行而不是文件末尾
【问题讨论】:
标签: python subprocess stdout pipe readline