查找子进程的执行时间.Popen Python

Rdr*_*s09 5 multithreading subprocess timeout python-2.x python-multithreading

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

proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT,  # Merge stdout and stderr 
stdout=subprocess.PIPE,
shell=True)
Run Code Online (Sandbox Code Playgroud)

子进程模块不支持执行时间,并且如果它超过特定阈值=>超时(杀死运行时间超过X秒的进程的能力)

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

MOP*_*3OB 5

好问题。这是完整的代码:

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.
Run Code Online (Sandbox Code Playgroud)