1

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.

Moonshile
  • 37
  • 6

1 Answers1

2

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
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • there could be [buffering issues in the child](http://stackoverflow.com/q/20503671/4279) (there is none due to implicit flush on `endl` in this case) and in the parent (your script). The latter you could fix using `p.stdin.flush()` or `bufsize=1` on Python 3 where `bufsize` is non-zero by default. – jfs May 09 '15 at 14:59