6

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.

2
  • stackoverflow.com/questions/1258566/… might help you with input. Commented Aug 15, 2013 at 17:05
  • "I am in superuser because I don't have to register and stuff but here we go.." - just fyi, that's not acceptable. Why do you think it's ok to post on a wrong site just so you don't have to register on another one?! Commented Aug 16, 2013 at 16:48

2 Answers 2

6

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!

Sign up to request clarification or add additional context in comments.

Comments

0

It sounds like what you're looking for is a while loop based off of the input. If you put a list of desired states into an array, then you can check the input each time to see if it is one of the inputs you are trying to catch.

z = getch()
chars = [9, 27]
while ord(z) not in chars:
  z = getch()

if ord(z) == 9:
  do_something()
if ord(z) == 27:
  do_something_else()

do_more_things()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.