jlconlin
jlconlin

Reputation: 15084

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?

Upvotes: 3

Views: 1748

Answers (2)

Lily Mara
Lily Mara

Reputation: 4138

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]

Upvotes: 2

Kostas Pelelis
Kostas Pelelis

Reputation: 1342

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

Upvotes: 1

Related Questions