redirecting sdtout/sdterr in a daemon

Rajarshi Guha rxg218 at
Tue Oct 30 17:01:09 CET 2001

  I'm using the module to make my code run as a daemon. 
However the module contains the lines:

sys.stdout = NullDevice()
sys.stderr = NullDevice()

Instead of this behaviour I would like it to write output to a file. So I 

sys.stderr = open(outputhandle,'w')
sys.stdout = open(outputhandle,'w')

Where outputhandl is a passed to the function. However no output comes to 
the this file. In addition when i try and print anything from the function, 
nothing is output.

How can I fix this problem. Below is the code for
def become_daemon(ourHomeDir='.'):
        """Robustly turn us into a UNIX daemon, running in ourHomeDir.
        XXX on SVR4 some claim you should re-fork after the setsid()
        jjk  06/25/97  001
        import os
        import sys
        if os.fork() != 0:  # launch child and...
                os._exit(0)     # kill off parent
        sys.stdout = NullDevice()
        sys.stderr = NullDevice()
        for z in range(3, 256):
                try: os.close(z)
                except: pass

class NullDevice:
        """A substitute for stdout and stderr that writes to nowhere
        jjk  06/25/97  001

        def write(self, s):
                """accept a write command, but do nothing
                jjk  06/25/97  001

Rajarshi Guha                  | email: rajarshi at
152 Davey Laboratory           | web  : 
Department of Chemistry        | ICQ  : 123242928
Pennsylvania State University  | AIM  : LoverOfPanda
GPG Fingerprint: DCCB 4D1A 5A8B 2F5A B5F6  1F9E CDC4 5574 9017 AF2A 
Public Key     :
COBOL is for morons.
                -- E.W. Dijkstra

More information about the Python-list mailing list