Redirect stdout & stderr (similar to a daemon)

Tsai Li Ming mailinglist at ltsai.com
Sun May 30 08:02:22 EDT 2004


Dear all,

I have a problem with a redirecting stdout and stderr. I am a top level 
module and has no control over the imported modules that are making 
system calls such as os.system or popen2.* . I have tried the simplest 
method of capturing stdout, stderr via:

saveout = sys.stdout
sys.stdout = file_obj

print 1 # works
os.system('w') # Doesn't work

sys.stdout = saveout
print 1 # Restored

------------------------------------------------

Therefore, I changed to the following method, similar
to a daemon. However, I couldn't find a way to restore back stdout and 
stderr.

import os
import sys

stdin = '/dev/null'
stdout = '/tmp/out.txt'
stderr = stdout

# Doesn't work
saveout = sys.stdout

si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)

# Redirect standard file descriptors.
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())

# Gets written to /tmp/out.txt
os.system('no_such_command')
os.system('w')


# How to do restoration of stdout and stderr
os.system('w')
print "Hello there"

Many thanks
Liming



More information about the Python-list mailing list