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]

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.