0

I have an issue with writing the output of a program when it also prompts for user input.

In write_output.py:

content = [str(i+1)+' blabla'*50 for i in range(200)]
for line in content:
    print line
a = raw_input('Write something:\n')
print 'You wrote:',a

In show_output.py:

from subprocess import Popen,PIPE

popen = Popen(['python','write_output.py'],stdout=PIPE,stderr=PIPE)
for line in iter(popen.stdout.readline,''):
    print line
popen.wait()

The output of show_output.py stops at line 197, but you can still give the input value and it will print out the rest

If I just use 'blabla' instead of 'blabla'*50, show_output.py prints nothing, and again the input can still be given and everything will be printed out.

If I comment out the last two lines in write_output.py, then show_output.py writes everything as expected in both cases.

Can someone explain what is going on?

Why does asking for input changes the stdout of subprocess?

Seb
  • 1,765
  • 9
  • 23
  • 2
    A few things to try that are common sources of issues: flush stdout after each print in `write_output.py` and call python using the `-u` switch for unbuffered mode (e.g. `Popen(['python', '-u', ...`) ([see this related](https://stackoverflow.com/questions/14258500/python-significance-of-u-option)). – jedwards Jul 04 '18 at 22:47
  • @jedwards this indeed fixes the issue for the example I gave, am I doomed if I can't control the buffer output of the subprocess child? (my use case has a .exe file instead of write_output.py) – Seb Jul 04 '18 at 23:31
  • I wouldn't say you're doomed. There are often os-specific tricks you can do with the streams to help solve any issues that might arise when using the real child subprocess. You might also find some guidance in looking at how libraries like [pexpect](https://pexpect.readthedocs.io/en/stable/) do things. – jedwards Jul 04 '18 at 23:50
  • You can add `bufsize=0` keyword argument to your `Popen()` call which forces (or should, I hope this is true for all platforms) unbuffered stdin/out/err (the former two are normally line buffered). – Ondrej K. Jul 05 '18 at 12:49

0 Answers0