[Tutor] run in "deamon" mode?

Reed O'Brien reed at reedobrien.com
Thu Jan 10 15:00:51 CET 2008

On Jan 10, 2008, at 12:41 AM, Allen Fowler wrote:

> Hello,
> How can a make a python script run in "deamon mode"? (on a linux box)
> That is, I want to run the program via "python myfile.py" and have  
> it drop me back to the command line.  The program should continue  
> running until I kill it via it's PID, the machine shuts down, or  
> the program itself decides to shutdown.   It should _not_  die when  
> I simply log-out, etc.
> Is there a standard library module to help with this?

Something I have thrown into scripts to daemonize them. NOTE: this is  
probably not the `best` way.  but it works...

import os
import sys

def daemonize():
	"""Become a daemon, seperate from the terminal and redirect IO"""
	if os.fork(): os._exit(0)
	os.setuid(1) # set user to  daemon
	sys.stdin  = sys.__stdin__  = open('/dev/null','r')
	sys.stdout = sys.__stdout__ = open('/dev/null','w')
	sys.stdout = sys.__stderr__ = sys.stdout

Then when you start your program in say main()

call daemonize()

More information about the Tutor mailing list