对于带有Try的循环,除非继续到循环范围结束



我已经编写了一个for循环来重试pyautogui.locateOnScreen语句,直到它找到图像为止。由于某种原因,即使在最初的几次尝试中找到了图像,代码也会循环通过所有20个周期。有人看到问题了吗?

for x in range(0, 20):  
try:
if pyautogui.locateOnScreen("PPTTTW.png", region=(537, 682, 93, 325)):  
print("found")
str_error = None
except Exception as str_error:
pass
if str_error:
sleep(0.5)  
else:
break

一种更简单的编写方法是将break语句直接放在try块中,只有当而不是引发异常时才能到达。

for _ in range(20):  
try:
if pyautogui.locateOnScreen("PPTTTW.png", region=(537, 682, 93, 325)):  
print("found")
break
except Exception as str_error:
logging.warning("Got %s, retrying...", str_error)
sleep(0.5)
else:
logging.error("Never found")

如果您不想在找到循环后继续,请在相应的If语句中使用break:

for x in range(0, 20):  
try:
if pyautogui.locateOnScreen("PPTTTW.png", region=(537, 682, 93, 325)):  
print("found")
str_error = None
break
except Exception as str_error:
pass
if str_error:
sleep(0.5)  
else:
break

但你确定你甚至需要一个for循环吗?因为我根本没看到你在里面用x

最新更新