【问题标题】:Find execution time for subprocess.Popen python查找 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 的最简单方法是什么?

【问题讨论】:

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


    【解决方案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.
    

    【讨论】:

      猜你喜欢
      • 2013-11-13
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2013-04-14
      • 2021-08-05
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多