Redirect stdout & stderr (similar to a daemon)

Tsai Li Ming mailinglist at ltsai.com
Sun May 30 10:13:49 EDT 2004


Mel Wilson wrote:
> In article <40b9cd69 at news.starhub.net.sg>,
> Tsai Li Ming <mailinglist at ltsai.com> wrote:
> 
>>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
> 
> 
>    I think the problem here is that os.system runs a
> shell with its own new set of process parameters,
> including its own stdin, stdout, etc.
> 
>    I would try one of the os.exec's or os.spawn's here
> instead.
> 
> 
>>[ ... ]
>># 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())
> 
> 
>    These modify the actual file objects represented by
> 'sys.stdin', etc.  There's no coming back from that.
> 
>         Regards.        Mel.

I would think so too. Sadly, I can't use other system calls because I 
will be importing other modules that I have no control of.

Liming



More information about the Python-list mailing list