How to Setup Python Script Autorun As a Service in Ubuntu 18.04

Setup Autorun a Python Script Using Systemd in Ubuntu 18.04

Create Python Application

$ sudo vi /usr/bin/test_service.py

Write some code :

#!/usr/bin/python3

import time

while True:
    print "This is a test python file!"
    time.sleep(2)

Create Service File

The file must have .service extension under /lib/systemd/system/ directory

$ sudo vi /lib/systemd/system/test-py.service

Add some contant with python full path and description

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

[Service]
Type=simple
ExecStart=/usr/bin/python /home/root/test_service.py
StandardInput=tty-force

[Install]
WantedBy=multi-user.target

Enable Newly Added Linux Service

Reload the systemctl daemon to read new file. You need to reload this deamon each time after making any changes in in .service file.

$ sudo systemctl daemon-reload

Now enable and start your new service

$ sudo systemctl enable test-py.service
$ sudo systemctl start test-py.service

Start/Restart/Status of Your New Service

For service status:

$ sudo systemctl status test-py.service
● test-py.service - Test Service
   Loaded: loaded (/lib/systemd/system/test-py.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2020-02-28 14:57:03 IST; 2s ago
 Main PID: 32454 (python)
    Tasks: 1 (limit: 4915)
   CGroup: /system.slice/test-py.service
           └─32454 /usr/bin/python /home/root/redis-key-expiry.py

Feb 28 14:57:03 websofttechs-MS-7C02 systemd[1]: Started Test Service.

Below commands to stop, start and restart your service manual.

$ sudo systemctl stop dummy.service          #To stop running service 
$ sudo systemctl start dummy.service         #To start running service 
$ sudo systemctl restart dummy.service       #To restart running service 

Reference : https://tecadmin.net/setup-autorun-python-script-using-systemd/

Leave a Reply