Using module 'subprocess' with timeout

后端 未结 29 2783
旧巷少年郎
旧巷少年郎 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:04

    You can do this using select

    import subprocess
    from datetime import datetime
    from select import select
    
    def call_with_timeout(cmd, timeout):
        started = datetime.now()
        sp = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        while True:
            p = select([sp.stdout], [], [], timeout)
            if p[0]:
                p[0][0].read()
            ret = sp.poll()
            if ret is not None:
                return ret
            if (datetime.now()-started).total_seconds() > timeout:
                sp.kill()
                return None
    

提交回复
热议问题