time.sleep 试验的替代方案?

time.sleep alternatives for trials?

在 python 上是否有 time.sleep 的替代方案,我可以在其中 运行 函数超时?

因为我有这些代码:

time.sleep(10)
pyautogui.locateCenterOnScreen('back.PNG')
pyautogui.click(120, 320)

它的作用是在 10 秒后 运行 成为 pyautogui

我想要的是一开始就运行 pyautogui 试玩10秒。如果图像未在 10 秒内定位,则将 return 错误。

是这样的吗?

for _ in range(10):
    pos = pyautogui.locateCenterOnScreen('back.PNG')
    if pos: break
    time.sleep(1)

if not pos: raise Exception('Where is this image?!')

pyautogui.click(*pos)

注意:可能需要超过 10 秒的时间,您可以用时间来代替

如果 locateCenterOnScreen 需要一段时间会好一些

from datetime import datetime
start = datetime.now()
pos = None
while (datetime.now() - start).total_seconds() < 10 and not pos:
    pos = pyautogui.locateCenterOnScreen('back.PNG')

if not pos: raise Exception('Where is the image!!??')

pyautogui.click(*pos)

或者包裹在函数中

def retry(action, max_secs=10):
    from datetime import datetime
    start = datetime.now()
    res = None
    while (datetime.now() - start).total_seconds() < max_secs:
        res = action()
        if res: return res
    raise Exception('Timeout!')

pos = retry(lambda: pyautogui.locateCenterOnScreen('back.PNG'))
pyautogui.click(*pos)

甚至“更好”地在函数外引发异常:

def retry(action, max_secs=10):
    from datetime import datetime
    start = datetime.now()
    res = None
    while (datetime.now() - start).total_seconds() < max_secs:
        res = action()
        if res: break
    return res

pos = retry(lambda: pyautogui.locateCenterOnScreen('back.PNG'))
if not pos: raise Exception('Where is this image??!!')
pyautogui.click(*pos)