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

已安装getch库但Python导入时出现ImportError报错该如何解决?

错误根因

你安装的原版getch库已停止维护,仅适配Python 2。其底层C扩展调用的Py_InitModule是Python 2专属的C API,Python 3版本已经完全移除该接口,因此导入时会抛出未定义符号错误。

修复步骤
  • 先卸载已安装的不兼容版本:
    pip uninstall -y getch
  • 选择以下任意一种方案适配Python 3:

    方案1:安装Python 3适配版getch

    执行命令安装getch3,这是官方原版getch的Python 3适配分支:
    pip install getch3
    安装完成后原有导入代码from getch import getch无需修改即可正常运行。

    方案2:手动实现getch功能(无需额外安装依赖)

    如果你不想新增第三方依赖,可以直接在代码中实现getch逻辑,Linux/macOS环境下可用以下代码:
    import sys
    import tty
    import termios
    
    def getch():
        fd = sys.stdin.fileno()
        old_attr = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_attr)
    
    Windows环境下直接调用系统内置的msvcrt模块即可:
    import msvcrt
    def getch():
        return msvcrt.getch().decode()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:54:06