kennethreitz-archive / procs

Python, Processes, and Prana.
225 stars 7 forks source link

Idea: generators that timeout #8

Open epaulson opened 10 years ago

epaulson commented 10 years ago

I don't write a ton in python, so there's almost certainly a more pythonic way to do this, but I once needed to wrap a daemon that printed out some startup information (and sadly didn't dump it to a file), but could take a while to do so, and I wanted to watch the progress as it went along. If it took more than about 20 seconds, something was almost certainly wrong and the subprocess was usually dead.

The code looked something like this

# run this command
sp = Process(executable = 'daemon', args = ['daemon', 'command'], shell=False, stdout_log = stdoutlog, stderr_log = stderrlog)

# collect debug info for 20 seconds
debug_info = sp.readallgen(20)
for line in debug_info:
  info = matcher.findall(line)
  if info:
      print "FOUND THE LINE WE ARE LOOKING FOR!: " + info[0]
  print line.rstrip()

print "Should be done with startup"
if sp.wait(os.WNOHANG) is None: 
  print "Process is still running, startup seems to have gone normally"
else:
  print "Process is gone, something must have gone horribly wrong"