已安装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环境下可用以下代码:
Windows环境下直接调用系统内置的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)msvcrt模块即可:import msvcrt def getch(): return msvcrt.getch().decode()
内容的提问来源于stack exchange,提问作者PawnShopChessboard
相关产品推荐
相关产品推荐

