Lan Do
Lan Do

Reputation: 63

Process hangs when communicating with an interactive program

I have created a simple echo.py like this:

import sys

while True:
    s = sys.stdin.readline()
    s = s.strip('\n')
    if s == 'exit':
        break

    sys.stdout.write("You typed: %s\n" % s)

It works well on the terminal.

And another program to interact with echo.py named main.py

import subprocess

if __name__ == '__main__':
    proc = subprocess.Popen(['python', 'echo.py'],stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,stderr=subprocess.PIPE)

    proc.stdin.write(b'Hello\n')
    proc.stdin.flush()
    print(proc.stdout.readline())

    proc.stdin.write(b'Hello World\n')
    proc.stdin.flush()
    print(proc.stdout.readline())

    proc.terminate()

The main.py just hangs forever. The thing is if I create subprocess with ['python', '-i'], it works.

Upvotes: 1

Views: 139

Answers (2)

Zach Thompson
Zach Thompson

Reputation: 322

Add sys.stdout.flush() to echo.py. Buffering works differently if you run the process with Popen instead of the terminal.

Upvotes: 1

cmyui
cmyui

Reputation: 81

I believe the problem is the while loop.. You're opening a subprocess, writing to it and flushing, and it does all that, but never finishes readline() because of the loop.

Upvotes: 0

Related Questions