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

MacBook Air M2上Pynput键盘监听器无法正常工作求助

问题解决方案

一、Accessibility权限的深层配置调整

你已给Anaconda添加权限,但可能遗漏了关键进程,按以下步骤补全:

  • 添加Python解释器权限:打开「系统设置」→「隐私与安全性」→「辅助功能」,点击+号,通过终端执行which python3找到Python路径,将该路径对应的程序添加到权限列表。
  • 补全Spyder关联的Python进程权限:找到Anaconda环境内的Python执行文件(比如/Users/你的用户名/opt/anaconda3/bin/python3),添加到辅助功能权限中。
  • 重置权限缓存:若添加后仍无效,终端执行:
    tccutil reset Accessibility
    
    重启系统设置后重新手动添加所需进程权限。

二、升级Pynput适配新环境

Ventura系统与M2芯片对旧版Pynput兼容性较差,升级到最新稳定版:

pip install --upgrade pynput

Anaconda环境用户可改用conda命令:

conda install -c conda-forge pynput --upgrade

三、修复终端段错误问题

终端段错误多与架构不兼容或系统限制有关:

  • 检查Python架构:终端执行python3 -c "import platform; print(platform.machine())",若输出为x86_64说明使用的是Rosetta转译版本,需重新下载安装适配M系列芯片的ARM版Anaconda。
  • 临时禁用SIP测试(谨慎操作,测试后建议恢复):重启Mac时按住Command+R进入恢复模式,终端执行:
    csrutil disable
    
    重启后运行代码验证,若恢复正常,说明是SIP限制了Pynput的底层访问,后续可重新启用SIP并通过正确权限配置解决。

四、代码优化(避免潜在异常)

原代码文件管理存在中途报错无法关闭的风险,改用with语句自动管理文件:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pyperclip
import os
import os.path
from pynput.keyboard import Key, Listener
from striprtf import striprtf
import re


def replace_words(string, dictionary):
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string


SAVE_FILE = input("Name of clipboard file: ")

save_path = "/Users/username/Clipboard"
FileName = os.path.join(save_path, SAVE_FILE+".txt")         

# 用with自动处理文件关闭
with open(FileName, "w") as f:
    def on_release(key):
        print("f")
        if str(key) == "'c'":
            print('Copying the slected')
            text = pyperclip.paste()
            print(text)
            text = striprtf(text)
            text = text.replace('\n\n', '\n')
            print(text)
            f.write(text+"\n")

        print('{0} release'.format(key))
        if key == Key.esc:
            print("End")
            return False

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

内容的提问来源于stack exchange,提问作者Tomas Storås

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:40:37