PvRecorder 在 systemd 服务中运行时抛出错误

PvRecorder 在 systemd 服务中运行时抛出错误

我正在努力奔跑录像机在装有 Ubuntu 23.04 的 Raspberry Pi 4 上使用 Python 脚本,单独运行时运行良好,但当我使用 systemd 服务运行它时,它会抛出错误。这是我的 Python 脚本 (test.py):

#! /home/kuri/Kuri/bin/python
from pvrecorder import PvRecorder

recorder = PvRecorder(device_index=-1, frame_length=512)

我使用虚拟信封来运行脚本。正常运行时它运行得很好,但是当我在此服务(chatbot.service)中运行它时:

[Unit]
Description=Chatbot service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/home/kuri/Kuri/bin/python /home/kuri/Kuri/test.py
WorkingDirectory=/home/kuri/Kuri

[Install]
WantedBy=multi-user.target

当我运行该服务时,它会引发以下错误:

chatbot.service - Chatbot Service
    Loaded: loaded (/lib/systemd/system/chatbot.service; enabled; preset: enabled)
    Active: failed (Result: exit-code) since Sun 2023-05-28 15:19:37 EDT; 51min ago
   Duration: 716ms
    Process: 872 ExecStart=/home/kuri/Kuri/bin/python /home/kuri/Kuri/test.py (code=exited, status=1/FAILURE)
   Main PID: 872 (code=exited, status=1/FAILURE)
        CPU: 288ms

May 28 15:19:37 kuri python[872]: ALSA lib pcm_dsnoop.c:566:(snd_pcm_dsnoop_open) unable to open slave
May 28 15:19:37 kuri python[872]: Traceback (most recent call last):
May 28 15:19:37 kuri python[872]:   File "/home/kuri/Kuri/test.py", line 4, in <module>
May 28 15:19:37 kuri python[872]:   recorder = PvRecorder(device_index=-1, frame_length=512)
May 28 15:19:37 kuri python[872]:               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
May 28 15:19:37 kuri python[872]:   File "/home/kuri/Kuri/lib/python3.11/site-packages/pvrecorder/pvrecorder.py", line 81 in __init__
May 28 15:19:37 kuri python[872]:   raise self._PVRECORDER_STATUS_TO_EXCEPTION[status]("Failed to initialize pv_recorder.")
May 28 15:19:37 kuri python[872]: RuntimeError: Failed to initialize pv_recorder.
May 28 15:19:37 kuri systemd[1]: chatbot.service: Main process exited, code=exited, status=1/FAILURE
May 28 15:19:37 kuri systemd[1]: chatbot.service: Failed with result 'exit-code'.

为什么这些错误仅在作为服务运行时才会抛出?我该怎么做才能解决这个问题?

答案1

当我使用 pvrecorder 时也遇到同样的错误。

无需设置具体的device_index,可以通过PvRecorder.get_avaliable_devices()获取设备索引

当您使用 systemd 启动应用程序时,录音机设备 ID 会有所不同。

相关内容