在 python 循环中调节
Coditioning in python loops
import time
import pyautogui
location = pyautogui.locateOnScreen('ok.png')
pyautogui.click(location)
如何将以下语句编写为代码?
如果在屏幕上找不到图像,请保持运行 location
直到找到图像。
否则代码将立即终止。
我试过了:
While location == None : #Or location == False
pyautogui.click(location)
尝试像这样使用 while
:
while location is not None:
pyautogui.click(location)
If the image can’t be found on the screen, locateOnScreen()
raises 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)
import time
import pyautogui
location = pyautogui.locateOnScreen('ok.png')
pyautogui.click(location)
如何将以下语句编写为代码?
如果在屏幕上找不到图像,请保持运行 location
直到找到图像。
否则代码将立即终止。
我试过了:
While location == None : #Or location == False
pyautogui.click(location)
尝试像这样使用 while
:
while location is not None:
pyautogui.click(location)
If the image can’t be found on the screen,
locateOnScreen()
raisesImageNotFoundException
这意味着您必须处理错误消息才能保留程序 运行,以防图像不存在。 尝试使用异常处理:
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)