[Tutor] how to redirect sys.__stdout__ back to screen in IDLE
alan.gauld@bt.com
alan.gauld@bt.com
Thu Nov 21 07:20:16 2002
> I tried several times on Python Shell (IDLE 0.8)
Aha! The penny drops. That's the problem, you are using IDLE.
Look at this:
>>> import sys
>>> sys.stdout
<PyShell.PseudoFile instance at 0x00A8CA60>
>>> sys.__stdout__
<open file '<stdout>', mode 'w' at 0x007554A0>
>>>
sys.__stdout__ holds the original stdout value when
Python starts. However, IDLE replaces sys.stdout with
its own stream. Thus you are replacing the IDLE stdout
with a file then trying to restore the *original*
console stdout, not the IDLE one.
In IDLE you need to save stdout yourself:
>>> old = sys.stdout
>>> sys.stdout = open("text.txt",'w')
>>> old.write(`sys.stdout`)
<open file 'text.txt', mode 'w' at 0x00ABB0E0>
>>> print 'bye!'
>>> sys.stdout = old
>>> sys.stdout
<PyShell.PseudoFile instance at 0x00A8CA60>
This will then restore IDLEs stdout correctly as you can see.
The advantage of this technique is that it should work whether
inside IDLE or not since externally oldOut will be the same
as __stdout__
The great thing about the >>> prompt is it lets you examine
your environment to see whats happening, learn to use that
functionality and it helps a lot...
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld