【问题标题】:How can I make one function of a while loop execute every x amount of seconds while not pausing the rest of the code? Python如何使 while 循环的一个函数每 x 秒执行一次,同时不暂停其余代码? Python
【发布时间】:2020-04-08 13:52:52
【问题描述】:

我 3 个月前才开始学习编程,如果这个问题听起来很愚蠢,我很抱歉。 我在这里尝试做的是让我的计算机每 5 秒单击一次左键,而不会暂停 while 循环,以便它继续读取屏幕。

我尝试使用 time.sleep(5)(但它会暂停该功能),而这个 'py.click(x, y, clicks=2, interval=5)' 也可以做同样的事情。

import numpy as np
from PIL import ImageGrab
import cv2
import time
import pyautogui as py


def screen_record():
    while True:
        printscreen1 = np.array(ImageGrab.grab(bbox=(0, 40, 800, 600)))
        printscreen2 = np.array(ImageGrab.grab(bbox=(0, 40, 800, 600)))
        diff = cv2.absdiff(printscreen1, printscreen2)
        grey = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
        blur = cv2.GaussianBlur(grey, (5, 5), 0)
        _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
        dilated = cv2.dilate(thresh, None, iterations=3)
        contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        for contour in contours:
            (x, y, w, h) = cv2.boundingRect(contour)
            if cv2.contourArea(contour) < 700:
                continue
            else:
                # py.click(x, y, clicks=2, interval=5)
                # time.sleep(5)
                cv2.rectangle(printscreen1, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # cv2.drawContours(printscreen1, contours, -1, (0, 255, 0), 2)

        cv2.imshow('feed', printscreen1)

        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break


screen_record()

【问题讨论】:

    标签: python-3.x opencv


    【解决方案1】:

    你可以使用例如 threading.Timer

    import threading
    import time
    
    run = True
    
    def main_loop():
        global run
        while run:
            try:
                time.sleep(1)
                print('main loop')
            except KeyboardInterrupt:
                 run = False
                 print('main loop FIN')    
                 break
    
    def fn_start():
        global run
        if run:
            print('Click')
            s_timer()
        else:
            print('timer FIN')
            return    
    
    def s_timer():
        t = threading.Timer(5.0, fn_start)
        t.start()
    
    
    
    s_timer()
    main_loop()
    
    

    【讨论】:

    • 谢谢你的建议,这里的问题是,如果你把这个函数放在一个while循环中,它会创建一个队列X次循环在函数休眠时尝试激活它,并且然后函数连续执行X次。
    • 你不需要把定时器放在while循环里面。我编辑了答案。请阅读docs.python.org/2/library/threading.html#timer-objects 只需将 s_timer() 放在 screen_record() 之前
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2018-03-15
    • 2019-03-20
    相关资源
    最近更新 更多