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/

Write some code :


import time

while True:
    print "This is a test python file!"

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

Description=Test Service

ExecStart=/usr/bin/python /home/root/


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/

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 :

Leave a Reply