【问题标题】:Coditioning in python loopspython循环中的条件
【发布时间】:2021-03-19 15:28:05
【问题描述】:
import time
import pyautogui
location = pyautogui.locateOnScreen('ok.png')
pyautogui.click(location)
如何将以下语句编写为代码?
如果屏幕上没有找到图像,请继续运行location,直到找到图像。
否则代码将立即终止。
我试过了:
While location == None : #Or location == False
pyautogui.click(location)
【问题讨论】:
标签:
python
loops
screen
screenshot
pyautogui
【解决方案1】:
尝试像这样使用while:
while location is not None:
pyautogui.click(location)
【解决方案2】:
根据Pyautogui documentation:
如果在屏幕上找不到图像,locateOnScreen() 会引发 ImageNotFoundException
这意味着您必须处理错误消息,以便在图像不存在的情况下保持程序运行。
尝试使用异常处理:
import pyautogui
while True:
# Try to do this
try:
location = pyautogui.locateOnScreen('ok.png')
# Location found with no errors: break the while loop and proceed
break
# If an error has occurred (image not found), keep waiting
except:
pass
pyautogui.click(location)
注意:这会生成一个无限循环,直到在屏幕上找到图像。要中断此循环并停止脚本执行,请在 Shell 上使用 CTRL+C。
或者,您可以设置等待图像的最长时间:
import time
import pyautogui
max_wait = 30 # Seconds
end = time.time() + max_wait
while time.time() <= end:
# Try to do this
try:
location = pyautogui.locateOnScreen('ok.png')
# Location found with no errors: break the while loop and proceed
break
# If an error has occurred (image not found), keep waiting
except:
pass
pyautogui.click(location)