1
votes

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.

  1. Use subprocess.Popen, and treat stdout or stdin of the subprocess as a file, write into stdin ('\n' is needed), and read from stdout with readline

  2. Use a library pexpect.

1
Can't you just read the stdout of the subprocess? - James Mills
For those of us who don't read C++, you should mention what that output looks like; specifically, is it terminated with a newline? - PM 2Ring
If use subprocess.Popen module, and read directly, it will keep waiting and do nothing. - Moonshile
don't put an answer into your question. You may post your own answer if you'd like. - jfs

1 Answers

1
votes

Using subprocess.Popen():

>>> import subprocess
>>> p = subprocess.Popen(['/your/cpp/program'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> p.stdin.write('1\n')
>>> p.stdout.readline()
'1\n'
>>> p.stdin.write('10\n')
>>> p.stdout.readline()
'10\n'
>>> p.stdin.write('0\n')
>>> p.stdout.readline()
''
>>> p.wait()
0