Python - Detect keypress
keyboard, python
Solution
One of the ways that you could do it is to create a new thread to run the key detector. Here's an example:
import threading
class KeyEventThread(threading.Thread):
def run(self):
# your while-loop here
kethread = KeyEventThread()
kethread.start()
Note that the while loop will not run until you call the thread's start() function. Also, it will not repeat the function automatically - you must wrap your code in a while-loop for it to repeat.
Do not call the thread's run() function explicitly, as that will cause the code to run in-line with all of the other code, not in a separate thread. You must use the start() function defined in threading.Thread so it can create the new thread.
Also note: If you plan on using the atexit module, creating new threads will make that module not work correctly. Just a heads-up. :)
I hope this helped!
Problem
I have an application and I want whenever the user presses RETURN/ENTER it goes to a def with an input. I am using this code: ``` while True: z = getch() # escape key to exit if ord(z) == 9: self.command() break if ord(z) == 27: print "Encerrando processo.." time.sleep(2) sys.exit() break ``` But it just blocks there and If I have more code it won't run it, only if the while is broken. I can't use tkinter either! Is there anything that only runs if the key is pressed? Without looping.