Using module 'subprocess' with timeout

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

    I've modified sussudio answer. Now function returns: (returncode, stdout, stderr, timeout) - stdout and stderr is decoded to utf-8 string

    def kill_proc(proc, timeout):
      timeout["value"] = True
      proc.kill()
    
    def run(cmd, timeout_sec):
      proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      timeout = {"value": False}
      timer = Timer(timeout_sec, kill_proc, [proc, timeout])
      timer.start()
      stdout, stderr = proc.communicate()
      timer.cancel()
      return proc.returncode, stdout.decode("utf-8"), stderr.decode("utf-8"), timeout["value"]
    

提交回复
热议问题