Python Popen (). Stdout.read () freezes

I am trying to get the output of another script using Python subprocess.Popen as follows

 process = Popen(command, stdout=PIPE, shell=True) exitcode = process.wait() output = process.stdout.read() # hangs here 

It freezes in the third line only when I run it as a python script and I cannot play it in the python shell.

Another script prints just a few words, and I assume this is not a buffer problem.

Does anyone have an idea of ​​what I'm doing wrong here?

+6
source share
2 answers

You might want to use .communicate() rather than .wait() plus .read() . Note the wait() warning on the subprocess documentation page:

Warning This will be inhibited when using stdout=PIPE and / or stderr=PIPE , and the child process generates sufficient output to the channel so that it blocks waiting for the OS buffer to receive more data. Use communicate() to avoid this.

http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait

0
source

read () waits for EOF before returning.

You can:

  • Wait for the subprocess to die, and then read () will return.
  • use readline () if your output is broken into lines (it still hangs if there are no output lines).
  • use os.read (F, N), which returns no more than N bytes from F, but will still block if the channel is empty (if O_NONBLOCK is not set to fd).
0
source

All Articles