Friday 7 September 2012

python 3 non-blocking read key input for windows using getch()


from msvcrt import kbhit,getch
#import time
stop = False
while not stop:
    print ("Hello world!")
    if kbhit():
        #print ('kbhit')
        #time.sleep(0.25)
        #print (getch())
        stop = getch()==bytes('q','ascii')

from msvcrt import kbhit,getch
import time
stop = False
while not stop:
    #print ("Hello world!")
    time.sleep(0.1)
    if kbhit():
        #print ('kbhit')
        #print (getch())
        #stop = getch()==bytes('q','ascii')
        stop = getch()==bytes('\r','ascii')



from msvcrt import kbhit,getch
import time, sys, threading, re
key = ""
terminate_this = 0
class MyThreadWithArgs(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global key, terminate_this
        while True:
            time.sleep(0.01)
            if terminate_this == 1:
                break
            if kbhit():
                key = ord(getch())
                print(key)
                if terminate_this == 1:
                    break
##                    if key == 113:
##                        return
            pass
        return
try:
    t = MyThreadWithArgs()
    t.start()
    print (t)
    while threading.active_count() > 1:
        print ('do something here')
        time.sleep(0.5)
        if key == 113: # 'q' key to quit
            terminate_this = 1
            break
        if key == 97: # 'a' key
            print ('do something for a')
            key = ""
            pass
        pass
except KeyboardInterrupt: #ctrl+c
    terminate_this = 1
    sys.exit()
sys.exit()






No comments:

Labels

Search This Blog