Suppose there is a program that produces different outputs with different inputs, and terminates if the input is a specific value. For example, it can be written in C++:
int main() {
int i;
while(true) {
cin >> i;
if (i) cout << i << endl;
else break;
}
return 0;
}
In this program, if you type a integer, it will print it on the screen. The program never terminates until you type a 0
.
Then how can I fetch the stdout corresponding to a stdin immediately with Python? That is, if I give a '1' into the stdin, I will expect to fetch a '1' from the stdout at once, while the process hasn't terminated yet.
Conclusion: There are two way to implement this.
Use
subprocess.Popen
, and treat stdout or stdin of the subprocess as a file, write into stdin ('\n'
is needed), and read from stdout withreadline
Use a library pexpect.