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 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

No one has commented on this page yet.

RSS feed for comments on this page