Search code examples
pythonubuntuservicepygamesystemd

Ubuntu systemd service for pygame


I have written a simple code with python and pygame to display some images at my monitor. When I run it, everything works fine. i tried to make it run at system startup with systemd services. here is my service:

[Unit]
Description=Starts pygame

[Service]
User=rplab
WorkingDirectory=/home/myuser/
ExecStart=/bin/bash /home/myuser/MyPygame.sh
KillMode=process

[Install]
WantedBy=multi-user.target 

When the system boots, it will start the service but unfortunately when I checked the service with systemd status, it gives this error:

pygame.error: No available video device

it seems as if it starts too soon that can't find my monitor, is it possible that I make the service start after the user logs in so that it can find my monitor?


Solution

  • The service file needs to tell systemd that it needs to start after user-session and graphical environment.

    [Unit]
    Description=Starts pygame
    Wants=systemd-logind.service systemd-user-sessions.service display-manager.service
    After=systemd-logind.service systemd-user-sessions.service display-manager.service
    
    [Service]
    ....
    ....
    
    [Install]
    WantedBy=graphical.target
    

    Make sure you are running a graphical.target as the default.

    $ systemctl set-default graphical.target