jlconlin jlconlin - 3 months ago 25
Python Question

Python - kill hung process started using subprocess.Popen

I've started a subprocess using:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate()[0]


Sometimes the command
cmd
hangs so my Python script also hangs at this point.

I'd like to let this run for a time (10 seconds?) and if I don't get a response, then simply kill the process and continue on with my script.

How can I do this?

Answer

If you're using python 3, Popen.communicate has a timeout kwarg:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate(timeout=10)[0]