使用Pynput侦听器暂停并继续执行脚本

时间:2019-09-25 13:53:04

标签: listener pynput

所以我有这个:

from pynput.keyboard import Key, Controller, Listener
keyboard = Controller()
import random
import time

def mainfunction():
    key1 = input("type first key to be repeated: ")
    key2 = input("second.. : ")
    key3 = input("last .. : ")
    x = 0
    while x < 10000:
        keyboard.press(key1)
        keyboard.release(key1)
        time.sleep((random.randint(1, 8))/10)
        keyboard.press(key2)
        keyboard.release(key2)
        time.sleep((random.randint(1, 8))/10)
        keyboard.press(key3)
        keyboard.release(key3)
        time.sleep((random.randint(1, 8))/10)
        x = x + 1


mainfunction()

我希望它暂停并继续按两次任意字母,但是不知道如何使用pynput.listener进行操作。

1 个答案:

答案 0 :(得分:0)

from pynput.keyboard import Key, Controller, Listener
keyboard = Controller()
from threading import Thread
import random
import time

def listen(key):
    global keyletter
    global key4
    keydata = str(key)

    try:
        if keydata.replace("'", "") == str(key4):
            keyletter = keydata.replace("'", "")
    except:
        #at Programstart key4 is not defined jet and would lead to an Error
        pass


def mainThread():
    global keyletter
    global key4
    key1 = input("type first key to be repeated: ")
    key2 = input("second.. : ")
    key3 = input("last.. : ")
    key4 = input("interrupt.. ")
    bool_interrupt = False
    x = 0
    while x < 10000:

        if keyletter == str(key4):
            if bool_interrupt == False:
                bool_interrupt = True
                time.sleep(0.5)
                keyletter = ""
            else:
                bool_interrupt = False
                time.sleep(0.5)
                keyletter = ""
        if bool_interrupt == False:
            keyboard.press(key1)
            keyboard.release(key1)
            time.sleep((random.randint(1, 8))/10)
            keyboard.press(key2)
            keyboard.release(key2)
            time.sleep((random.randint(1, 8))/10)
            keyboard.press(key3)
            keyboard.release(key3)
            time.sleep((random.randint(1, 8))/10)
            x = x + 1

def listenerThread():
    global keyletter
    keyletter = ""
    with Listener(on_press=listen) as l:
        l.join()

myThread1 = Thread(target=mainThread)
myThread2 = Thread(target=listenerThread)

myThread1.start()
myThread2.start()

这可能太复杂了,但是可以。 我使用第二个线程,因为侦听器会停止代码直到输入。 这样,mainThread循环,而listenerThread等待输入。