Using module 'subprocess' with timeout

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

    This solution kills the process tree in case of shell=True, passes parameters to the process (or not), has a timeout and gets the stdout, stderr and process output of the call back (it uses psutil for the kill_proc_tree). This was based on several solutions posted in SO including jcollado's. Posting in response to comments by Anson and jradice in jcollado's answer. Tested in Windows Srvr 2012 and Ubuntu 14.04. Please note that for Ubuntu you need to change the parent.children(...) call to parent.get_children(...).

    def kill_proc_tree(pid, including_parent=True):
      parent = psutil.Process(pid)
      children = parent.children(recursive=True)
      for child in children:
        child.kill()
      psutil.wait_procs(children, timeout=5)
      if including_parent:
        parent.kill()
        parent.wait(5)
    
    def run_with_timeout(cmd, current_dir, cmd_parms, timeout):
      def target():
        process = subprocess.Popen(cmd, cwd=current_dir, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
    
        # wait for the process to terminate
        if (cmd_parms == ""):
          out, err = process.communicate()
        else:
          out, err = process.communicate(cmd_parms)
        errcode = process.returncode
    
      thread = Thread(target=target)
      thread.start()
    
      thread.join(timeout)
      if thread.is_alive():
        me = os.getpid()
        kill_proc_tree(me, including_parent=False)
        thread.join()
    

提交回复
热议问题