在Python中根据指定时间使用Try-Except
我正在使用Marathon(一个Java桌面应用测试工具)来自动化回归测试。Marathon使用Jython,这样我就可以同时使用Java库和Python库。在我的脚本中,当我填写某些字段时,基于我之前输入的值,可能会出现(或不出现)不同的字段。我需要跳过那些不存在的字段,原因很明显。当字段被禁用但仍然存在时,这没问题,因为我可以使用
if Component.isEnabled():
#do something
else:
#do something
问题在于当某个组件根本不存在时。我想知道在Java中有没有办法检查一个组件是否存在?比如,Component.exists()
这个方法就很适合我的需求,但组件类中并没有这样的方法。
我更希望通过使用if Component.exists():
这样的语句来解决我的问题,但我可以通过try和except块来绕过这个问题。不过,这样做会导致脚本的执行时间大幅增加。它会尝试查找组件大约2到3分钟,然后才抛出异常。我能想到的解决办法是,如果有类似try for x seconds
的语句,如果找不到组件就继续执行。有没有办法限制尝试某个语句的时间?
2 个回答
1
这是解决你问题的方法:
import signal
def time_out(self):
def signal_handler(signum, frame):
raise Exception("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(3)
all_games = []
try:
while True:
#do what you want to do
except Exception as msg:
print msg
3是函数超时的时间
祝好,Shlomy
2
我在网上找到了一段代码,可以在你的代码中抛出一个超时异常,这是对另一个StackOverflow问题的回答:如果socket.setdefaulttimeout()不起作用,我该怎么办?,不过这段代码只适用于Linux系统,链接里有说明。
具体来说:
import signal, time
class Timeout():
"""Timeout class using ALARM signal"""
class Timeout(Exception): pass
def __init__(self, sec):
self.sec = sec
def __enter__(self):
signal.signal(signal.SIGALRM, self.raise_timeout)
signal.alarm(self.sec)
def __exit__(self, *args):
signal.alarm(0) # disable alarm
def raise_timeout(self, *args):
raise Timeout.Timeout()
# Run block of code with timeouts
try:
with Timeout(60):
#do something
except Timeout.Timeout:
#do something else
这段代码会尝试“做某件事”,如果执行时间超过60秒,就会停止继续执行...