redirection in a file with os.system

TP Tribulations at Paralleles.invalid
Mon Nov 3 20:06:02 CET 2008

Hi everybody,

The following code does not redirect the output of os.system("ls") in a

import sys, os
saveout = sys.stdout
fd = open( 'toto', 'w' )
sys.stdout = fd
os.system( "ls" )
sys.stdout = saveout

Whereas the following works:

old_stdout = os.dup( sys.stdout.fileno() )
fd = 'bar', os.O_CREAT | os.O_WRONLY )
os.dup2( fd, sys.stdout.fileno() )
os.system( "ls" )
os.close( fd )
os.dup2( old_stdout, sys.stdout.fileno() )


I have another question: with this last code using, the problem is
that the file 'bar' is not removed before being written. So, it could lead
to errors: the file 'bar' is overwritten, but extra lines from previous
executions could remain.
Am I compelled to use os.unlink (or os.remove) before calling



python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)

More information about the Python-list mailing list