Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
jlconlin Avatar asked Mar 06 '26 20:03

jlconlin


2 Answers

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]
like image 132
Lily Mara Avatar answered Mar 09 '26 09:03

Lily Mara


From subprocess documentation proc.terminate() is what you 're looking for

like image 21
Kostas Pelelis Avatar answered Mar 09 '26 09:03

Kostas Pelelis