1

這裏的Python代碼運行任意命令返回它的標準輸出的數據,或者提高對非零退出代碼的異常:查找執行時間subprocess.Popen蟒蛇

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

的子模塊不支持執行如果它超過特定的閾值=>超時(能夠殺死運行時間超過X秒的進程)

什麼是最簡單的方式來實現在Linux2.6上運行的get_execution_time和timeout ?

回答

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.