MacOS Mojave下Python keyboard库报错Error 13,sudo命令含义咨询
Hey there! Let's break down your problem step by step, from the permission error to fixing the logic in your code.
为什么会弹出「Error 13 - Must be run as administrator」?
On MacOS, system-level operations like listening to global keyboard input require elevated permissions. The keyboard module needs to hook into the system's keyboard events, which regular user accounts don't have access to by default. That's exactly why you're hitting this OSError.
什么是sudo命令?
sudo stands for Superuser Do — it lets you run commands with the privileges of the system's root (administrator) user. Using sudo gives your Python script the necessary permissions to access MacOS's keyboard monitoring features, which will fix the Error 13.
解决方法
1. 用sudo运行你的脚本
Open your terminal, navigate to the folder where your script is saved, then run:
sudo python3 your_script_name.py
When prompted, enter your Mac user password (you won't see any characters as you type — this is normal for terminal password prompts).
2. 修正你的代码逻辑
Your current code has a couple of logic issues that will prevent it from working even after fixing permissions:
- The function
function_that_checks_if_q_is_pressed()doesn't return a value, so checkingfunction_that_checks_if_q_is_pressed == Truewill never be true. - You're calling the function twice in each loop iteration, which means it will wait for two key presses instead of one.
Here's the corrected version:
import keyboard def function_that_checks_if_q_is_pressed(): pressed_key = keyboard.read_key() if pressed_key == "q": print(True) return True return False while True: # Call the function once per loop and check its return value if function_that_checks_if_q_is_pressed(): break
3. 允许终端访问输入监控权限
MacOS might prompt you to allow Terminal access to input monitoring. If you see this prompt, click "Open System Preferences", go to Security & Privacy > Privacy > Input Monitoring, and check the box next to Terminal. You may need to restart Terminal for this change to take effect.
注意事项
- Only use
sudowith scripts you trust — running a script as root gives it full access to your system, which can be risky if the code is untrusted. - If you still run into issues, make sure you've installed the
keyboardmodule correctly (you can re-install it withsudo pip3 install keyboardto ensure it's set up with admin privileges).
内容的提问来源于stack exchange,提问作者Raz P

