查找subprocess.Popen python的执行时间

时间:2017-08-03 19:15:39

标签: multithreading timeout subprocess python-2.x python-multithreading

这是运行任意命令返回其stdout数据的Python代码,或者在非零退出代码上引发异常:

proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT,  # Merge stdout and stderr 
stdout=subprocess.PIPE,
shell=True)

子进程模块不支持执行时间,如果超过特定阈值=>超时(能够终止运行超过X秒的进程)

在Python2.6程序中实现get_execution_time和timeout的最简单方法是在Linux上运行吗?

1 个答案:

答案 0 :(得分:0)

好问题。以下是完整的代码:

import time, subprocess                                   # Importing modules.

timeoutInSeconds = 1                                      # Our timeout value.

cmd   =  "sleep 5"                                        # Your desired command.
proc  =  subprocess.Popen(cmd,shell=True)                 # Starting main process.

timeStarted = time.time()                                 # Save start time.

cmdTimer     =  "sleep "+str(timeoutInSeconds)            # Waiting for timeout...
cmdKill      =  "kill "+str(proc.pid)+" 2>/dev/null"      # And killing process.
cmdTimeout   =  cmdTimer+" && "+cmdKill                   # Combine commands above.
procTimeout  =  subprocess.Popen(cmdTimeout,shell=True)   # Start timeout process.

proc.communicate()                                        # Process is finished.

timeDelta = time.time() - timeStarted                     # Get execution time.
print("Finished process in "+str(timeDelta)+" seconds.")  # Output result.