[英]Python run Subprocess for certain time
我正在測試某個exe文件,並且想為我的腳本實現一種確定它已進入無限循環的方法。 這是我當前的代碼:
import subprocess
import os
import sys
runs = 1000 # Default run is 1000
if len(sys.argv)>1: # If I want to change the num of runs
runs = int(sys.argv[1])
FNULL = open(os.devnull, 'w')
logfile = open('logfile', 'w')
args = "exe" # Exe to test
succ = 0
fail = 0
for i in range (0,runs):
if subprocess.call(args,stdout = logfile, stderr = FNULL) == 100:
succ += 1 # If returned 100 then success
else:
fail += 1 # Else Failed
break # Break on failure
open('logfile', 'w').close() # Empties the file
print "Succ: %d , Fail: %d" % (succ, fail)
可以說我定義了一個無限循環,因為我的exe運行時間超過5秒。 我將如何實施呢? 感謝您提供任何幫助,包括當前代碼的提示!
啟動一個threading.Timer
,它將在5秒鍾后終止該進程,並報告該行為已完成。 您需要在不同的步驟中創建並等待該過程,因此請使用Popen
對象而不是call
。 我創建了一個測試程序,該程序使用sleep模擬您的無限列表。
import subprocess
import os
import sys
import threading
def on_timeout(proc, status_dict):
"""Kill process on timeout and note as status_dict['timeout']=True"""
# a container used to pass status back to calling thread
status_dict['timeout'] = True
print("timed out")
proc.kill()
runs = 1000 # Default run is 1000
if len(sys.argv)>1: # If I want to change the num of runs
runs = int(sys.argv[1])
FNULL = open(os.devnull, 'w')
logfile = open('logfile', 'w')
# replacing example with a running program. This is a simple python
# we can call from the command line.
# args = "exe" # Exe to test
test_script = "import time;import sys;time.sleep(%d);sys.exit(100)"
succ = 0
fail = 0
for i in range (0,runs):
# set by timer
status_dict = {'timeout':False}
# test prog sleeps i seconds
args = ["python", "-c", test_script % i]
proc = subprocess.Popen(args,
stdout = logfile, stderr = FNULL)
# trigger timout and kill process in 5 seconds
timer = threading.Timer(5, on_timeout, (proc, status_dict))
timer.start()
proc.wait()
# in case we didn't hit timeout
timer.cancel()
print status_dict
if not status_dict['timeout'] and proc.returncode == 100:
succ += 1 # If returned 100 then success
else:
fail += 1 # Else Failed
break # Break on failure
open('logfile', 'w').close() # Empties the file
print "Succ: %d , Fail: %d" % (succ, fail)
這對我有用
import subprocess
import time
for _ in range(999999): # or whatever
p1 = subprocess.Popen(['exe_file', 'arg1', 'arg2'])
time.sleep(0.1) # wait a small amount of time, hopefully the process ends fast
return_code = p1.poll()
if return_code is not None: # we're happy, the process ended fast
... # do something to celebrate
else: # we're sad. let the process run for at most 5 seconds
time.sleep(5)
p1.terminate() # this kills the process. try p1.kill() too...
p1.wait() # this cleans up the process registry.
免責聲明:這是linux代碼。 Windows上的情況可能有所不同,但是您可以先檢查一下,然后在這里https://docs.python.org/2/library/subprocess.html閱讀有關子進程庫以及linux和Windows之間差異的內容。
在python3.3中,超時被添加到subprocess.call中。 如果您使用的是python3.3,則可以更改subprocess.call以將超時作為參數:
subprocess.call(args,stdout = logfile, stderr = FNULL, timeout=5)
如果您使用的是python2.7,則可以使用subprocess32軟件包,或者需要編寫一些額外的代碼來處理超時。
如果安裝subprocess32模塊,則可以使用上述subprocess.call方法,並將超時作為參數。
另外,此代碼可以幫助您實現相同的功能:
from subprocess import Popen
timeout=5 #5 seconds
p = Popen(args, shell = True, stdout = logfile, stderr = FNULL)
while (p.poll() is None and timeout > 0):
time.sleep(1)
timeout-=1
if timeout <= 0:
p.terminate() #Timeout
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.