Ubuntu安装pygame后无法运行代码 视频系统未初始化报错
问题现象
Ubuntu环境下通过pip install pygame完成安装,执行pygame --version校验显示安装成功,但无法运行《Python Crash Course》教材中的pygame相关代码,也无法运行官方示例命令python3 -m pygame.examples.aliens。
执行示例命令时输出如下报错:
pygame 2.1.2 (SDL 2.0.16, Python 3.8.10) Hello from the pygame community. https://www.pygame.org/contribute.html shared memfd open() failed: Function not implemented ALSA lib confmisc.c:767:(parse_card) cannot find card '0' ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory ALSA lib conf.c:5220:(snd_config_expand) Evaluate error: No such file or directory ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM default Warning, no sound Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/home/aidanrogers02/.local/lib/python3.8/site-packages/pygame/examples/aliens.py", line 400, in <module> main() File "/home/aidanrogers02/.local/lib/python3.8/site-packages/pygame/examples/aliens.py", line 243, in main bestdepth = pg.display.mode_ok(SCREENRECT.size, winstyle, 32) pygame.error: video system not initialized
报错原因
- 程序崩溃的核心原因是pygame视频子系统初始化失败,和前面的ALSA音频报错无关:音频报错仅代表系统未检测到可用声卡设备,pygame会自动降级为无声音模式,不会触发程序崩溃。
- 最常见的触发场景是在无图形界面支持的Ubuntu环境运行pygame:包括未开启WSLg的WSL2版本、Ubuntu Server纯命令行版本、未开启3D加速的精简虚拟机,这类环境下SDL图形库无法加载显示驱动,直接导致display模块初始化失败,报错里的
shared memfd open() failed就是WSL无GUI环境的典型特征。 - 少数情况是pip安装pygame时没有自动拉全SDL相关的系统依赖,导致图形模块无法正常调用系统接口。
解决方法
根据实际运行环境对应处理:
- 如果是WSL2运行Ubuntu:执行
wsl --update升级WSL到支持WSLg的版本,重启WSL获得原生GUI支持后即可正常运行pygame;不想升级WSL的话,换用带完整桌面的虚拟机或者原生Ubuntu双系统运行即可。 - 如果是原生桌面版Ubuntu/带完整桌面的虚拟机:先卸载pip安装的pygame,再通过系统apt源安装带全量依赖的pygame包,执行以下命令:
pip uninstall pygame -y sudo apt update sudo apt install python3-pygame -y - 如果是自行编写的pygame代码出现同类报错:检查代码逻辑,确保在调用任何
pygame.display相关接口前,已经执行pygame.init()完成全模块初始化。
内容的提问来源于stack exchange,提问作者thenewchalupa
相关产品推荐
相关产品推荐

