Daemonizing a Python Script

As my knowledge of Python continues to grow, I find myself using it more in my own systems. This is one of my more useful snippets of code; it allows a Python script to continue running as a daemon even if you log out or your session gets disconnected. A nice side effect of this is that the process is immediately run in the background, returning the user to a command prompt instantly.

I originally picked up the code to run a Python script as a daemon from the Python Cookbook on the ActiveState Programmer Network.

#! /usr/bin/env python from os import fork, chdir, setsid, umask from sys import exit def main(): while 1: #main daemon process loop # Dual fork hack to make process run as a daemon if __name__ == "__main__": try: pid = fork() if pid > 0: exit(0) except OSError, e: exit(1) chdir("/") setsid() umask(0) try: pid = fork() if pid > 0: exit(0) except OSError, e: exit(1) main()
Hope this is as useful to you as it is to me, Motoma

Post your comment

Comments

  • Great post! Thanks a lot. It was exactly what I was looking for.

    Posted by Casey, 08/05/2009 3:14am (10 months ago)

RSS feed for comments on this page