Pynput不会打印出我按的键

时间:2019-11-03 13:58:05

标签: python input pynput

我有以下代码

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))


def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

如果我对事情的理解正确,那么在运行此代码时,它将打印出我在键盘上按的所有键(我在Mac OS上运行该代码)。

但是,当我尝试按一些键时,该代码未打印任何内容。问题是什么?


我也尝试运行此代码

 from pynput import keyboard

def on_press(key):
    try: k = key.char # single-char keys
    except: k = key.name # other keys
    if key == keyboard.Key.esc: return False # stop listener
    if k in ['1', '2', 'left', 'right']: # keys interested
        print('Key pressed: ' + k)
        return False # remove this if want more keys

lis = keyboard.Listener(on_press=on_press)
lis.start() # start to listen on a separate thread
lis.join() # no this if main thread is polling self.keys

仍然没有运气。

0 个答案:

没有答案