查找 subprocess.Popen python 的执行时间
Posted
技术标签:
【中文标题】查找 subprocess.Popen python 的执行时间【英文标题】:Find execution time for subprocess.Popen python 【发布时间】:2018-01-11 13:33:36 【问题描述】:这是运行返回其标准输出数据的任意命令或在非零退出代码上引发异常的 Python 代码:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
子进程模块不支持执行时间,如果它超过特定阈值 => 超时(能够杀死运行超过 X 秒的进程)
在 Linux 上运行的 Python2.6 程序中实现 get_execution_time 和 timeout 的最简单方法是什么?
【问题讨论】:
【参考方案1】:好问题。这是完整的代码:
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.
【讨论】:
以上是关于查找 subprocess.Popen python 的执行时间的主要内容,如果未能解决你的问题,请参考以下文章
查找 subprocess.Popen python 的执行时间
python subprocess.popen stdin.write
subprocess.Popen("echo $HOME"... 和 subprocess.Popen(["echo", "$HOME"]