python - Pygame display init on headless Raspberry Pi Zero (Raspbian Buster Lite)

标签 python raspberry-pi pygame raspberry-pi-zero debian-buster

我有 Pi Zero 运行 Raspbian Buster Lite,没有连接显示器。它在启动时运行一个 python 程序(crontab @reboot 入口),像这样:

@reboot sudo su username/home/username/launcher.sh >>/home/username/crontab.log 2>&1

我必须初始化 pygame 显示,因为我需要处理 Sound 对象结束事件。如果不初始化显示,则不会触发事件。

代码在这一行中断,出现错误“pygame.error:无法打开控制台终端”

    os.putenv('SDL_VIDEODRIVER', 'dummy')
    pygame.display.init()  # error at this line

我的代码曾经在以前的 Raspbian (Stretch) 版本中工作。我尝试了各种驱动程序,添加/删除了 pygame.display.set_mode((1, 1)),但没有成功。

我知道其他帖子解决了同样的问题,但我已经用尽了所有这些方法 - 将驱动程序更改为 fbcon,跳过 set_mode 行等。唯一有效的方法是以 root 身份运行程序:

@reboot/home/username/launcher.sh >>/home/username/crontab.log 2>&1

但从安全角度来看,这是个坏主意。我宁愿以非特权用户身份运行它。

是否有一种新的 hack 可以让它通过 display.init()

最佳答案

pygame.init初始化所有 Pygame 模块。你不需要初始化所有的 Pygame 模块,只需要初始化你需要的那些。对于播放音乐,初始化 pygame.mixer 就足够了.一些例子

import pygame

pygame.mixer.init()
pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play()

while pygame.mixer.music.get_busy():
   pygame.time.delay(10)

pygame.mixer.quit()
import pygame

pygame.mixer.init()
my_sound = pygame.mixer.Sound('music.mp3')
my_sound.play(0)

while pygame.mixer.get_busy():
    pygame.time.delay(10)

pygame.quit()
import pygame.mixer

pygame.mixer.init()
my_sound = pygame.mixer.Sound('sound.wav')
my_sound.play(0)
pygame.time.wait(int(my_sound.get_length() * 1000))

pygame.mixer.quit()

但是,您不能使用事件模块,因为它绑定(bind)到显示模块。

关于python - Pygame display init on headless Raspberry Pi Zero (Raspbian Buster Lite),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57418067/

相关文章:

linux - startx 后自动运行脚本

python - 为什么 Surface.unlock 无法解锁表面以进行 blitting?

python - Pygame 和多处理策略

python - python 中的多项式除法

python - 在 bash、R、python 或 NCL 中将 hdf5 转换为 netcdf4?

python - Django 自定义身份验证模型无法从管理门户登录

python - 为什么这个寻路功能会崩溃?

python - Pyspark 数据框如何删除所有列中的空行?

linux - 旧 Raspberry Pi 镜像的克隆无法在 Raspberry Pi 3 上运行

python - 在Python中回车\r返回一个音符