Search code examples
pythonpython-3.xpynput

ImportError: cannot import name 'key' from 'pynput.keyboard'


In the first place I want to apologize if is this question dumb.

I have a problem with this error:

    ImportError: cannot import name 'key' from 'pynput.keyboard' 
    (C:\Users\richard\AppData\Local\Programs\Python\Python37-32\lib\site- 
    packages\pynput\keyboard\__init__.py)

Can you please tell me, how to fix it ?:

I tried find some advice on google, but I didn't find anything. Maybe it is just too dumb "problem".

This is the unfinished code, I wanted to try if it is working, then the error showed up.

import pynput

from pynput.keyboard import key, Listener

count = 0
keys = []

def on_press(key):
    global keys, count
    print("{0} pressed".format(key))

def write_file(keys):
    with open("log.txt", "w") as f:
        for key in keys:
            f.write(key)

def on_realease(key):
    if key == Key.esc:
        return False

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

This is the whole problem:

Traceback (most recent call last):
  File "C:/Users/richard/AppData/Local/Programs/Python/Python37- 
  32/Logger.py", line 3, in <module>
    from pynput.keyboard import key, Listener
ImportError: cannot import name 'key' from 'pynput.keyboard' 
(C:\Users\richard\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\pynput\keyboard\__init__.py)

Process finished with exit code 1

Solution

  • Its Key not key

    from pynput.keyboard import Key, Listener
    

    Take a look to the docs here.