In this tutorial I will starting one service using systemctl , python and systemd.
First, you need to create a file named
testpython.service .
[mythcat@desk system]# cd /etc/systemd/system/
[root@desk system]# vim testpython.service
This file is a configuration file for this service.
[Unit]
Description=Python Service
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/python /home/mythcat/test_service.py
[Install]
WantedBy=multi-user.target
Create the python file for this service. I named
test_service.py .
[root@desk system]# exit
exit
[mythcat@desk system]$ cd ~
[mythcat@desk ~]$ vim test_service.py
#!/usr/bin/env python
import logging
import time
logging.basicConfig(level="INFO")
while True:
logging.info("Hi")
time.sleep(3)
Change permissions file for this python file and
testpython.service, see:
[mythcat@desk ~]$ chmod 764 test_service.py
Because you run this service with systemd then selinux will send you error, fix that:
[mythcat@desk ~]$ chcon -t bin_t ~/test_service.py
Reload all services and start your service with this commands:
[root@desk system]# systemctl daemon-reload
[root@desk system]# systemctl start testpython.service
[root@desk system]# systemctl status testpython.service
● testpython.service - Python Service
Loaded: loaded (/etc/systemd/system/testpython.service; enabled; vendor>
Active: active (running) since Sat 2018-09-22 21:36:23 EEST; 5s ago
Main PID: 7213 (python)
Tasks: 1 (limit: 2102)
Memory: 5.7M
CGroup: /system.slice/testpython.service
└─7213 /usr/bin/python /home/mythcat/test_service.py
Sep 22 21:36:23 desk systemd[1]: Started Python Service.
Sep 22 21:36:24 desk python[7213]: INFO:root:Hi
Sep 22 21:36:27 desk python[7213]: INFO:root:Hi
You can use the
journalctl command to see the output of this service:
[root@desk system]# journalctl -u testpython.service
-- Logs begin at Sat 2018-09-22 20:40:06 EEST, end at Sat 2018-09-22 21:31:07 EEST. --
Sep 22 20:40:06 desk python[6232]: INFO:root:Hi
Sep 22 20:40:09 desk python[6232]: INFO:root:Hi
Sep 22 20:40:12 desk python[6232]: INFO:root:Hi
Sep 22 20:40:15 desk python[6232]: INFO:root:Hi
Sep 22 20:40:18 desk python[6232]: INFO:root:Hi
Sep 22 20:40:21 desk python[6232]: INFO:root:Hi
Sep 22 20:40:24 desk python[6232]: INFO:root:Hi
Sep 22 20:40:27 desk python[6232]: INFO:root:Hi
Sep 22 20:40:30 desk python[6232]: INFO:root:Hi
Let's see the result: