Putting together a small systemd service script and controlling python


This time I will demonstrate how to create a simple systemd service file so that you can control your applications with systemctl in CentOS 7. As you know systemctl will be replacing init so it is time to see what you can do with it.

Imagine the following sample script called hello.py. It will not do anything but print hello world and then sleep for one second.

Make sure you set the permissions so that it is executable. I will be placing this script in the folder /usr/local/bin/hello/

The next step is to create a small bash script that will execute the python script. In this script you can do more stuff if needed. I will call it run.sh

Make sure it is also located in /usr/local/bin/hello/

Now you want to be able to control that running a service command, i.e “service hello start” or
“systemctl start hello.service”

Start by navigating to the systemd folder and create the hello.service file. This is where we will tell systemctl what will happen.

Edit the hello.service file and make sure you point ExecStart to the bash script called run.sh

Now, there are a few things you need to know. The parameter “ExecStart” is what going to happen when you tell systemctl to “start”. There are also “ExecStop” and “ExecReload”. Those will be used for? You guessed it, when stopped and reloaded. There are also nice stuff such as “ExecStartPre” and “ExecStartPost” to execute commands before and after the main app has started.

More info can be found at Red Hat

However, in our service file above we only need the settings I have provided.
So now it is time to execute it:

As you see I am using the old service command but CentOS 7 is redirecting to systemctl, that is fine. Both will work. The status command also shows that it is running.

We can also confirm by checking what is running

If you change any of the contents of the hello.service file you will be given the following message:

That is fine, just execute “systemctl daemon-reload”

To enable this on startup you can just do the classic chkconfig hello on and systemctl will take over:

If you have a python application that may involve mongodb or some other service like mysql you can edit your service file to look like this

This will mean that syslog, network and the mongodb service is required to start before your app is.

Have fun!

One thought on “Putting together a small systemd service script and controlling python

Leave a Reply

Your email address will not be published. Required fields are marked *