Python Key press and Key Release Listener

前端 未结 2 2018
眼角桃花
眼角桃花 2021-01-01 00:08

I am controlling a remote toy car using python code .As of now the code is as below

def getkey():
        fd = sys.stdin.fileno()
        old = termios.tcget         


        
2条回答
  •  离开以前
    2021-01-01 00:47

    Faced a similar problem (I am no Python expert) but this worked for me

    import pynput
    from pynput import keyboard 
    
    def on_press(key):
        try:
            print('Key {0} pressed'.format(key.char))
            #Add your code to drive motor
        except AttributeError:
            print('Key {0} pressed'.format(key))
            #Add Code
    def on_release(key):
        print('{0} released'.format(key))
        #Add your code to stop motor
        if key == keyboard.Key.esc:
            # Stop listener
            # Stop the Robot Code
            return False
    
    # Collect events until released
    with keyboard.Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
    

提交回复
热议问题