我正在测试某个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秒。 我该如何实施这一点? 感谢您的帮助,包括关于当前代码的提示!在
在python3.3中,timeout被添加到subprocess.call. 如果您使用的是python3.3,那么您只需更改subprocess.call将超时作为参数:
如果您使用的是python2.7,您可以使用subprocess32包,或者需要编写一些额外的代码来处理超时。
如果安装subprocess32模块,则可以使用上述方法subprocess.call以超时为参数。
否则,此代码可以帮助您实现相同的功能:
^{pr2}$启动一个
threading.Timer
,它将在5秒后终止进程并报告该操作已完成。您将需要在不同的步骤中创建并等待进程,因此使用Popen
对象而不是call
。我创建了一个测试程序,用睡眠来模拟你的无限列表。这对我有用
免责声明:这是linux代码。windows上的情况可能有所不同,但您可以先检查一下,然后在这里阅读https://docs.python.org/2/library/subprocess.html关于子进程库以及linux和windows之间的区别的内容。
相关问题 更多 >
编程相关推荐