I have a simple c++ program that I'm trying to execute through a python script. (I'm very new to writing scripts) and I'm having trouble reading output through the pipe. From what I've seen, it seems like readline() won't work without EOF, but I want to be able to read in the middle of the program and have the script respond to whats being outputted. Instead of reading output, it just hangs the python script:
#!/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()
and the c++ file, which generates a random number between one and 100, then checks the users guess until they guess correctly
#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";
}
the eventual goal is to have the script solve the problem with a binary search, but for now I just want to be able to read a line without it being the end of the file