3

Well, I have two scripts. The a.py which prints the output of the b.py script as follows:

#a.py
from subprocess import Popen, PIPE, STDOUT

p = Popen(['/Users/damian/Desktop/b.py'], shell=False, stdout=PIPE, stderr=STDOUT)

while p.poll() is None:
    print p.stdout.readline()


#b.py
#!/usr/bin/env python
import time

while 1:
    print 'some output'
    #time.sleep(1)

This works.But, Why do my scripts deadlock when I uncomment the time.sleep() line?

ScotchAndSoda
  • 3,811
  • 4
  • 34
  • 38
  • Are you sure that b.py will not deadlock itself if executed separately? (check indentations if they are same for both lines in while 1: ! – przemo_li Oct 01 '12 at 19:37

2 Answers2

5

Your output is probably buffered. Add a .flush() for stdout to clear it:

import sys
import time

while 1:
    print 'someoutput'
    sys.stdout.flush()
    time.sleep(1)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

If you add -u to the call in a.py (make the output unbuffered) then you don't need to modify b.py script:

import sys
from subprocess import Popen, PIPE, STDOUT

p = Popen([sys.executable, '-u', '/Users/damian/Desktop/b.py'],
          stdout=PIPE, stderr=STDOUT, close_fds=True)
for line in iter(p.stdout.readline, ''):
    print line,
p.stdout.close()
if p.wait() != 0:
   raise RuntimeError("%r failed, exit status: %d" % (cmd, p.returncode))

See more ways to get output from a subprocess.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670