简体   繁体   中英

Bind keyboard event in python

Following code has loop that breaks automatically after 10 minutes, I want to break this loop manually, meaning I want to send keyboard events ( ctrl + shift + x) to break. How can I do it? Thank you for taking time to read this.

def mouseerr():
    timeout = time.time() + 60*10
    while 1:

        ctypes.windll.user32.SetCursorPos(0,0)
        if time.time() > timeout:
            break

You can use the pynput module to listen to keyboard inputs.

Install the module by running the console command pip install pynput . Then you can import the right piece of the module by writing into your script from pynput.keyboard import Listener, Key . Then you add with Listener(on_press=keypress,on_release=keyrelease) as listener: listener.join() the listener and define before this piece of code the two functions keypress and keyrelease with one input parameter which will give you back the pressed key. The method could break the loop then. Make sure to run this in an extra Thread to avoid freezing the rest of your code. As alternative, you can use pygame for this, but pynput is easier to implement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM