Swapping out sys.stdout globally

Steven Majewski sdm7g at Virginia.EDU
Fri Mar 1 13:44:31 EST 2002


On Fri, 1 Mar 2002, Skip Montanaro wrote:

>
>     Kevin> sys.stdout = NewFile()
>     Kevin> sys.stderr = NewFile()
>
>     Kevin> However, I have some logging routines in a separate package that
>     Kevin> already have their own references to sys.stdout and sys.stderr
>     Kevin> which are unaffected by this.
>
> Sounds like they use something like
>
>     from sys import stdout,stderr
>
> The best solution there would be for those packages to import sys in the
> usual fashion:
>
>     import sys
>
> and refer to sys.stdout & sys.stderr.
>


Skip's advice is sound.

However, if there's some reason you can't do that, if you're on unix
then you can use posix.close, posix.open & posix.dup2 to redirect
the posix file underneath the python file object.

Something like:

new_file = open( file, 'w' )
fd = sys.stdout.fileno()
os.close(fd)
os.dup2( new_file.fileno(), fd )

Don't use sys.stdout.close(), because it will mark the Python file
object as closed. os.close() closes the real os file but doesn't
mark the python file object as closed.


-- Steve Majewski






More information about the Python-list mailing list