5

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • http://stackoverflow.com/questions/1258566/how-to-get-user-input-during-a-while-loop-without-blocking might help you with input. – cptroot Aug 15 '13 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?! – ThiefMaster Aug 16 '13 at 16:48

2 Answers2

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!

DJ8X
  • 385
  • 4
  • 9
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()
cptroot
  • 321
  • 2
  • 6