I am trying to run PvRecorder on my Raspberry Pi 4 with Ubuntu 23.04 in a python script, and it works fine when run on its own, but when I run it using a systemd service, it throws errors.
This is my python script (test.py):
#! /home/kuri/Kuri/bin/python
from pvrecorder import PvRecorder
recorder = PvRecorder(device_index=-1, frame_length=512)
I use a virtual envelope to run the script. It runs perfectly fine when running normally, but when I run it in this service (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
When I run the service, it throws these errors:
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'.
Why are these errors only thrown when running as a service? What can I do to fix this?