Unix Daemon Python Library 0.0.1 Released

Another building block I’ve found useful having wanted to have processes run after the terminal session has ceased is the Unix style Daemon process.  This library provides a Python wrapper class.

The code was shamelessly borrowed from Sander Marechal’s “A simple unix/linux daemon in Python”.  Unfortunately his page no longer exists.

The library can be downloaded here.

The user should derive their own class from the Daemon class and implement the run method:

#!/usr/bin/env python

import sys, time
from daemon import Daemon

class MyDaemon(Daemon):
	def run(self):
		while True:
			time.sleep(1)

if __name__ == "__main__":
	daemon = MyDaemon('/tmp/daemon-example.pid')
	if len(sys.argv) == 2:
		if 'start' == sys.argv[1]:
			daemon.start()
		elif 'stop' == sys.argv[1]:
			daemon.stop()
		elif 'restart' == sys.argv[1]:
			daemon.restart()
		else:
			print "Unknown command"
			sys.exit(2)
		sys.exit(0)
	else:
		print "usage: %s start|stop|restart" % sys.argv[0]
		sys.exit(2)

Then the process can be started and stopped as follows:

# sudo python myprocess.py start
# sudo python myprocess.py stop
# sudo python myprocess.py restart

2 thoughts on “Unix Daemon Python Library 0.0.1 Released

  1. after running ‘sudo python setup.py install’, I attempted to implement your test code but received error stating: ImportError “cannot import name Daemon”

    There is no instance of Daemon in the daemon.py file that I can see. Am I doing something wrong here? Would love to use what seems to be a very elegant daemon solution. thanks in advance.

  2. As it says above, “The user should derive their own class from the Daemon class and implement the run method”.

    “cannot import name Daemon” looks to me like a problem finding where you’ve stored daemon.py in relation to your test script. I would suggest either looking at the Python documentation on how to install libraries or have everything in the same directory whilst your getting it working.

    Hope that helps.

Leave a Reply

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