如何使2个侦听器同时运行?

时间:2019-01-07 05:10:11

标签: python pynput

def on_press(key):
    log = open('log.txt', 'a+')
    log.write(strftime('[%a %b %d %Y %H:%M:%S] ') + format(key) + '\n')
    log.close()


def on_click(x, y, button, pressed):
    if pressed:
        pyautogui.screenshot(strftime('%a %d %b %Y %H-%M-%S.png'),
                             region=(pyautogui.position()[0] - 25, pyautogui.position()[1] - 25, 50, 50))


with mouse.Listener(on_click=on_click) and keyboard.Listener(on_press=on_press) as listener:
    listener.join()

如果我只运行mouse.Listener或keyboard.Listener,它就可以工作,但是如果我不尝试合并两者,则可以。我怎样才能解决这个问题? 对不起英语不好,非母语...

1 个答案:

答案 0 :(得分:0)

这不是将with与多个变量一起使用的方式。试试这个:

with mouse.Listener(on_click=on_click) as mouse_listener, keyboard.Listener(on_press=on_press) as keyboard_listener:

您还可以设置更好的格式:

with mouse.Listener(on_click=on_click) as mouse_listener, \
     keyboard.Listener(on_press=on_press) as keyboard_listener: