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

MacOS Mojave下Python keyboard库报错Error 13,sudo命令含义咨询

解决MacOS Mojave下Python keyboard模块的权限错误及代码修正

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 checking function_that_checks_if_q_is_pressed == True will 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 sudo with 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 keyboard module correctly (you can re-install it with sudo pip3 install keyboard to ensure it's set up with admin privileges).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:25:07