Using module 'subprocess' with timeout

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

    https://pypi.python.org/pypi/python-subprocess2 provides extensions to the subprocess module which allow you to wait up to a certain period of time, otherwise terminate.

    So, to wait up to 10 seconds for the process to terminate, otherwise kill:

    pipe  = subprocess.Popen('...')
    
    timeout =  10
    
    results = pipe.waitOrTerminate(timeout)
    

    This is compatible with both windows and unix. "results" is a dictionary, it contains "returnCode" which is the return of the app (or None if it had to be killed), as well as "actionTaken". which will be "SUBPROCESS2_PROCESS_COMPLETED" if the process completed normally, or a mask of "SUBPROCESS2_PROCESS_TERMINATED" and SUBPROCESS2_PROCESS_KILLED depending on action taken (see documentation for full details)

提交回复
热议问题