Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
75 lines (58 sloc) 2.45 KB

labels: Blog Python created: 2013-02-16T00:00 place: Starobilsk, Ukraine comments: true

Python way to create a unix daemon

We can easily put a program into background using '&':

python myprogram.py &

But that does not correctly detach the process from the terminal session that started it. So, if I'll close terminal, the program will be terminated.

Here are steps to create a proper daemon: http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC16.

python-daemon package allows us to create a proper unix daemon with ease.

This is a small example of a daemon that saves current time to file every 10 seconds:

# mydaemon.py
import os
import time

from daemon import runner
from datetime import datetime


class App():

    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path = '/var/run/mydaemon.pid'
        self.pidfile_timeout = 5

    def run(self):
        filepath = '/tmp/mydaemon/currenttime.txt'
        dirpath = os.path.dirname(filepath)
        while True:
            if not os.path.exists(dirpath) or not os.path.isdir(dirpath):
                os.makedirs(dirpath)
            f = open(filepath, 'w')
            f.write(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
            f.close()
            time.sleep(10)


app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

Usage:

> python mydaemon.py
usage: md.py start|stop|restart
> python mydaemon.py start
started with pid 8699
> python mydaemon.py stop
Terminating on signal 15

Links: