Python way to create a unix daemon

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

python &

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:

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:

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/'
        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):
            f = open(filepath, 'w')
            f.write(datetime.strftime(, '%Y-%m-%d %H:%M:%S'))

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


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


Licensed under CC BY-SA 3.0