树莓派systemd运行Python脚本报错:pygame/pyautogui初始化失败
问题:树莓派systemd服务运行Python脚本报错(pygame/pyautogui)
我有一个基于pygame和pyautogui开发的Python脚本,在树莓派3 Model B V1.2的终端或IDLE中运行完全正常,能实现打开网页、读取摇杆输入的功能。为了让脚本在网络连接完成后开机自启,我在/etc/systemd/system/目录下创建了systemd服务,但通过服务运行时,pygame和pyautogui均出现报错。
服务配置文件
[Unit] Description=My magic service After=multi-user.target Requires=network.target [Service] Type=simple User=pi ExecStart=/usr/bin/python3 /home/pi/FinalCode.py Restart=always StandardOutput=file:/tmp/FinalTests.log StandardError=inherit [Install] WantedBy=multi-user.target
报错信息
pygame报错
Traceback (most recent call last): File "/home/pi/FinalCode.py", line 89, in <module> for event in pygame.event.get(): # read joystick commands pygame.error: video system not initialized
pyautogui报错(注释pygame代码后)
Traceback (most recent call last): import pyautogui File "/home/pi/.local/lib/python3.9/site-packages/pyautogui/__init__.py", line 249, in <module> import mouseinfo File "/home/pi/.local/lib/python3.9/site-packages/mouseinfo/__init__.py", line 223, in <module> _display = Display(os.environ['DISPLAY']) File "/usr/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DISPLAY'
已确认终端和服务运行的Python环境一致:sys.prefix和sys.base_prefix均为/usr,且都通过/usr/bin/python3运行Python 3.9.2。
解决方法
问题核心是systemd服务默认运行在无图形会话的环境中,缺少DISPLAY等图形相关环境变量,而pygame、pyautogui依赖图形会话才能正常工作。
1. 修改服务配置,补充图形环境变量
在[Service]段中添加图形环境变量,并调整服务启动时机,确保在桌面环境和网络就绪后再启动:
[Unit] Description=My magic service After=graphical.target network.target Requires=network.target [Service] Type=simple User=pi Environment="DISPLAY=:0" Environment="XAUTHORITY=/home/pi/.Xauthority" ExecStart=/usr/bin/python3 /home/pi/FinalCode.py Restart=always StandardOutput=file:/tmp/FinalTests.log StandardError=inherit [Install] WantedBy=graphical.target
DISPLAY=:0:树莓派默认桌面的显示端口XAUTHORITY=/home/pi/.Xauthority:指定用户pi的图形认证文件路径After=graphical.target:确保服务在图形桌面启动后运行
2. 重新加载服务配置并启用
执行以下命令使修改生效:
sudo systemctl daemon-reload sudo systemctl enable your-service-name.service sudo systemctl start your-service-name.service
3. 额外排查(若仍有问题)
- 确保树莓派默认启动到图形桌面:运行
raspi-config,选择System Options→Boot / Auto Login→Desktop Autologin - 检查pygame初始化代码,即使不需要显示窗口,也要初始化视频系统:
pygame.init() # 初始化最小化无框窗口,避免视频系统未初始化报错 pygame.display.set_mode((1, 1), pygame.NOFRAME) joystick = pygame.joystick.Joystick(0) joystick.init()
内容的提问来源于stack exchange,提问作者atohal
相关产品推荐
相关产品推荐

