Systemd Python Script Fails to Start – No Error

pythonpython3servicessystemd

I wrote a python script that I would like to launch inside of screen

screen -d -m /usr/bin/python3 /home/kermit/active-climateMngr.py

which works just fine at the command line but when I try to begin it in systemd as a service, no screen session ever launches.

.service config:

[Unit]
Description=Test Service
After=multi-user.target
Conflicts=getty@tty1.service

[Service]
Type=simple
ExecStart=/usr/bin/screen -d -m /usr/bin/python3 /home/kermit/active-climateMngr.py
StandardInput=tty-force

[Install]
WantedBy=multi-user.target

systemd:

kermit@minnow:~ $ sudo service active-climateMngr.py status
● active-climateMngr.py.service - Test Service
   Loaded: loaded (/lib/systemd/system/active-climateMngr.py.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Sat 2021-02-20 08:58:46 CST; 4min 7s ago
  Process: 14373 ExecStart=/usr/bin/screen -d -m /usr/bin/python3 /home/kermit/active-climateMngr.py (code=exited, status=0/SUCCESS)
 Main PID: 14373 (code=exited, status=0/SUCCESS)

Feb 20 08:58:46 minnow.coinz.com systemd[1]: Started Test Service.
Feb 20 08:58:46 minnow.coinz.com systemd[1]: active-climateMngr.py.service: Succeeded.

screen:

kermit@minnow:~ $ screen -ls
No Sockets found in /run/screen/S-kermit.

How do I get systemd to launch a custom pythons script, in a screen session?

I was able to get the script to work without screen in systemd before, but now that no long works either.

I am using

sudo systemctl daemon-reload

with every change.

Best Answer

A systemd unit with Type=simple is expected to not fork into the background, but screen -d -m creates a new detached session in the background and exits. This causes systemd to regard the unit as dead and either kill the detached session or lose track of it. Use -D -m instead:

Type=simple
ExecStart=/usr/bin/screen -D -m …

The difference between those two options is explained in the manpage screen(1):

-d -m Start screen in "detached" mode. This creates a new session but doesn't attach to it. This is useful for system startup scripts.
-D -m This also starts screen in "detached" mode, but doesn't fork a new process. The command exits if the session terminates.

As the screen session runs as root if you don't include e.g. User=kermit in your systemd unit, you'll need to use sudo screen -ls to see the session.