redirection in a file with os.system
Arnaud Delobelle
arnodel at googlemail.com
Mon Nov 3 14:18:21 EST 2008
TP <Tribulations at Paralleles.invalid> writes:
> Hi everybody,
>
> The following code does not redirect the output of os.system("ls") in a
> file:
>
> import sys, os
> saveout = sys.stdout
> fd = open( 'toto', 'w' )
> sys.stdout = fd
> os.system( "ls" )
> sys.stdout = saveout
> fd.close()
>
> Whereas the following works:
>
> old_stdout = os.dup( sys.stdout.fileno() )
> fd = os.open( '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() )
>
> Why?
>
> I have another question: with this last code using os.open, 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
> os.system("ls")?
Do you have to use low level os functions? Why not use the subprocess
module? E.g
>>> subprocess.call('ls', stdout=open('toto', 'w')
HTH
--
Arnaud
More information about the Python-list
mailing list