Wait a subprocess for a given time, then terminate
Hi. I want to run some shell commands on linux machine with python Popen, for ex. "ping". How I can terminate the process, if it isn't finished normally in a given time?
I've tried write some code, can anybody improve it or give some better idea? Any suggestions appreciated. Thanx.
wait_sec = 10
import time
import subprocess
wForceKill = True
res = subprocess.Popen(self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for i in range(wait_sec):
time.sleep(1.0)
res.poll()
if res.returncode != None:
wForceKill = False
break
if wForceKill:
res.terminate()
print("Subprocess was killed!")
res_out = res.communicate()[0]
_neo_
Junior Poster in Training
64 posts since Aug 2010
Reputation Points: 26
Solved Threads: 3
There was an old solution on linux to kill a subprocess
# linux, mac
os.kill(pid, signal.SIGKILL)
killedpid, stat = os.waitpid(pid, os.WNOHANG)
if killedpid == 0:
print >> sys.stderr, "ACK! PROCESS NOT KILLED?"
however the Popen.terminate() method is more recent and probably does about the same. Also what you can do is try to read the stdout and stderr of your subprocess while it is running. I once found a very simple method to do this in linux. See this post http://www.daniweb.com/forums/post777876.html#post777876 .
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691