Python – daemons

Today a little post on how to create a daemon with python. I started from this article:  http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/  and then I added logging and scheduler.

Normally I don’t like to coerce sysadmins to install a lot of dependencies, so I try to put this way of thinking in this package.

Requirements:

  • python3

If you used ubuntu to install python3, install the following packages:

If you compiled python3 from source:

Install setproctitle. On ubuntu run:

From source run:

It’s not mandatory setproctitle, it only change the process name you will see with ps. If it is not installed, the daemon doesn’t care.

For the scheduler, I used apsscheduler, version 2.x

Compared to the article reported, I added a class to log std error and output even when daemon detach from console:

I added lib directory to python lib path to avoid system module installation

I configured logging for reading its configuration from file. The output is very detailed, but easy to chagne in conf/logging.conf.

I changed pidfile checks. In worker.py every functionality (now only scheduler) has its own process, so I need to manage closing more than a single pid. This is the block modified in daemon.py

I created worker class that override run method from daemon and launch the scheduler as a new process. As you can see, it is very easy to add other processes.

Bye!

daemon_skeleton.tar

Posted in Python, Tutorial.