-1

I use Popen() to spawn a program? That program will display 'text' at the program?

How can I monitor status of my program I spawn? How can I determine if there is nothing print out for 1 min, i assume the program is hang and I need to kill the process 'p'?

# command is my command to run
p = subprocess.Popen(command,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
michael
  • 106,540
  • 116
  • 246
  • 346

1 Answers1

0

This is largely based on Non-blocking read on a subprocess.PIPE in python

We use a separate thread and Queue to check for output after a certain amount of time, given in the q.get(timeout=5) portion. Change it to 60 if you only want to kill the process after 60 seconds. Change the first argument to subprocess.Popen to an appropriate command you want to run.

import Queue
import subprocess
import threading

def checkStdout(p, q):
    s = p.stdout.read(1)
    if len(s) > 0:
        q.put(s)

def run():
    p = subprocess.Popen(['cat'], stdout=subprocess.PIPE, close_fds=True)
    print 'pid %d started' % p.pid
    q = Queue.Queue()
    t = threading.Thread(target=checkStdout, args=(p, q))
    t.daemon = True
    t.start()
    try:
        canGet = q.get(timeout=5)
        print 'has output'
    except Queue.Empty:
        print 'no output'
        # kill process
        p.kill()

if __name__ == '__main__':
    run()
Community
  • 1
  • 1
yanhan
  • 3,507
  • 3
  • 28
  • 38
  • Thanks. I tired this in my script. I see 'has output'. But then the function run just return without waiting for p (the process running my command (replace your 'cat' in your example) to finish. – michael Aug 04 '13 at 18:21
  • Try adding a `p.communicate()` after the `print 'has output'`, I think that will wait for the process to terminate. http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate – yanhan Aug 05 '13 at 02:52