Using module 'subprocess' with timeout

后端 未结 29 2399
旧巷少年郎
旧巷少年郎 2020-11-21 15:15

Here\'s the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:

proc = subprocess.P         


        
29条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 15:58

    jcollado's answer can be simplified using the threading.Timer class:

    import shlex
    from subprocess import Popen, PIPE
    from threading import Timer
    
    def run(cmd, timeout_sec):
        proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
        timer = Timer(timeout_sec, proc.kill)
        try:
            timer.start()
            stdout, stderr = proc.communicate()
        finally:
            timer.cancel()
    
    # Examples: both take 1 second
    run("sleep 1", 5)  # process ends normally at 1 second
    run("sleep 5", 1)  # timeout happens at 1 second
    

提交回复
热议问题