Python subprocess timeout?

后端 未结 10 2121
旧时难觅i
旧时难觅i 2020-12-09 04:06

Is there any argument or options to setup a timeout for Python\'s subprocess.Popen method?

Something like this:

subprocess.Popen([\'..\'], ..., timeout

10条回答
  •  春和景丽
    2020-12-09 04:44

    A python subprocess auto-timeout is not built in, so you're going to have to build your own.

    This works for me on Ubuntu 12.10 running python 2.7.3

    Put this in a file called test.py

    #!/usr/bin/python
    import subprocess
    import threading
    
    class RunMyCmd(threading.Thread):
        def __init__(self, cmd, timeout):
            threading.Thread.__init__(self)
            self.cmd = cmd 
            self.timeout = timeout
    
        def run(self):
            self.p = subprocess.Popen(self.cmd)
            self.p.wait()
    
        def run_the_process(self):
            self.start()
            self.join(self.timeout)
    
            if self.is_alive():
                self.p.terminate()   #if your process needs a kill -9 to make 
                                     #it go away, use self.p.kill() here instead.
    
                self.join()
    
    RunMyCmd(["sleep", "20"], 3).run_the_process()
    

    Save it, and run it:

    python test.py
    

    The sleep 20 command takes 20 seconds to complete. If it doesn't terminate in 3 seconds (it won't) then the process is terminated.

    el@apollo:~$  python test.py 
    el@apollo:~$ 
    

    There is three seconds between when the process is run, and it is terminated.

提交回复
热议问题