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]