Using module 'subprocess' with timeout

后端 未结 29 2410
旧巷少年郎
旧巷少年郎 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 16:11

    Here is my solution, I was using Thread and Event:

    import subprocess
    from threading import Thread, Event
    
    def kill_on_timeout(done, timeout, proc):
        if not done.wait(timeout):
            proc.kill()
    
    def exec_command(command, timeout):
    
        done = Event()
        proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
        watcher = Thread(target=kill_on_timeout, args=(done, timeout, proc))
        watcher.daemon = True
        watcher.start()
    
        data, stderr = proc.communicate()
        done.set()
    
        return data, stderr, proc.returncode
    

    In action:

    In [2]: exec_command(['sleep', '10'], 5)
    Out[2]: ('', '', -9)
    
    In [3]: exec_command(['sleep', '10'], 11)
    Out[3]: ('', '', 0)
    

提交回复
热议问题