Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

python - pynput code doesn't give me a simple string as a key

I have this simple pynput code:

import pynput
from pynput.keyboard import Key, Listener

keys = []

def on_press(key):
    keys.append(key)
    write_file(keys)


def write_file(keys):

    allowed = ['7','9','1','3','4','5','6','q','w','e','z']
    with open('log.txt', 'w') as f:
        for key in keys:
            if key in allowed:
                # removing ''
                k = str(key).replace("'", "")
                f.write(k)

                f.write(',')

def on_release(key):

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


with Listener(on_press = on_press,
        on_release = on_release) as listener:

    listener.join()

When I run this and enter 7 on my keypad, I would expect it to write 7 into log.txt because it is in the allowed list. But it doesn't. I traced it using import pdb and pdb.set_trace() and when I manually type in

'7' in allowed

I get a True

But when I use

key in allowed

I get a False even though key is '7'. I suspect it has to do with type because when I use

type(key)

I get

<class 'pynput.keyboard._xorg.KeyCode'>

So I'm thinking I have to just make key a normal and boring string. But

str(key)

still won't say that it is in the allowed list.

I tried looking at the documentation for pynput regarding KeyCode, but I don't think that is helping me. Maybe someone else knows how to make this work?

question from:https://stackoverflow.com/questions/65645324/pynput-code-doesnt-give-me-a-simple-string-as-a-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to compare

key.char == '7' 

but it gives error when key doesn't have .char - i.e. Ctrl, Alt, Shift, etc. and even Space - so safer is to compare

key == KeyCode.from_char('7')

from pynput.keyboard import Listener, Key, KeyCode


def on_press(key):
    try:
        print('from_char:', key == KeyCode.from_char('7'))
        print('key.char :', key.char == '7')
    except Exception as ex:
        print('Error:', ex)


def on_release(key):

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


with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

EDIT:

from pynput.keyboard import Listener, Key, KeyCode


#allowed = [KeyCode.from_char('7'), KeyCode.from_char('9')]
#allowed = [KeyCode.from_char(char) for char in ['7','9','1','3','4','5','6','q','w','e','z']]
allowed = [KeyCode.from_char(char) for char in '7913456qwez']
    
def on_press(key):
    try:
        print('allowed:', key in allowed)
    except Exception as ex:
        print('Error:', ex)


def on_release(key):

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


with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...