Keep python script running by systemd service
#### 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@your_user_name.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@your_user_name.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=
`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@your_user_name.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@your_user_name.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=