Search code examples
pythonserviceraspberry-pi3systemd

Issues running working python script from systemd on Raspberry Pi


I have a python script, using pygame and pyautogui which works when run through terminal or any IDLE on my Raspberry Pi 3 Model B V1.2. The script opens a webpage, and reads joystick inputs through pygame.

I want the script to run at boot after a network is connected, so have created a service in /etc/systemd/system/.

When run by the service, the script has an error when using various libraries including pygame and pyautogui.

My service is as follows:

[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

The welcome message from pygame prints (Hello from the pygame community... etc), however it the returns the following error:

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

I then commented out all the pygame, but a similar issue also occurs with pyautogui, which returns the following error:

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'

I have checked "sys.prefix" and "sys.base_prefix" and both in the terminal and from the service they are "/usr" (I think this shows that it is running in the same environment?). Both the service and idle/terminal are running Python 3.9.2 through "/usr/bin/python3"

How do I get the systemd service to run in exactly the same way as the terminal or IDLE running the script?


Solution

  • Found a solution that works, the issue was as bbenne10 suggested.

    With hindsight, somewhat unsurprisingly, pyautogui also needs the display so had no issues afterwards.