Skip to content

Instantly share code, notes, and snippets.

@yingshaoxo
Last active January 6, 2018 15:12
Show Gist options
  • Save yingshaoxo/9b027ace63cf9982fe22320539bb6c95 to your computer and use it in GitHub Desktop.
Save yingshaoxo/9b027ace63cf9982fe22320539bb6c95 to your computer and use it in GitHub Desktop.
Keep python script running by systemd service (how to keep program running in linux)

0. write a python script

vim time_logger.py

import os
import logging
import time

current_dir = os.path.abspath(os.path.dirname(__file__))

logging.basicConfig(filename=os.path.join(current_dir, 'whatsup.log'), level=logging.INFO)

now = time.strftime("%H:%M:%S")
logging.info(now + '\n')
time.sleep(3)

1. create a service file

vim /lib/systemd/system/my_python.service

[Unit]
Description=My first python service
#After=multi-user.target

[Service]
Type=idle
ExecStart=/usr/bin/python /root/Codes/Python/time_logger.py
Restart=always
#RestartSec=1

[Install]
WantedBy=multi-user.target

2. reload deamon and enable our service

systemctl daemon-reload

systemctl enable my_python.service

3. reboot and check

reboot

go to the python script folder and run cat whatsup.log constantly, you will see current time logging.

4. links may help:

https://gist.github.com/ewenchou/be496b2b73be801fd85267ef5471458c

https://www.raspberrypi-spy.co.uk/2015/10/how-to-autorun-a-python-script-on-boot-using-systemd/

https://stackoverflow.com/questions/18086896/running-a-persistent-python-script-from-systemd

https://www.freedesktop.org/software/systemd/man/systemd.service.html#Restart=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment