Start New Discussion within our Software Development Community

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):
                if res.returncode != None:
                    wForceKill = False
            if wForceKill: 
                print("Subprocess was killed!")
            res_out = res.communicate()[0]

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

This question has already been answered. Start a new discussion instead.