[Python-ideas] Replacing the standard IO streams (was Re: changing sys.stdout encoding)

Paul Moore p.f.moore at gmail.com
Sat Jun 9 15:00:03 CEST 2012

On 9 June 2012 12:00, Paul Moore <p.f.moore at gmail.com> wrote:
> On 9 June 2012 10:55, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> So, after much digging, it appears the *right* way to replace a
>> standard stream in Python 3 after application start is to do the
>> following:
>>    sys.stdin = open(sys.stdin.fileno(), 'r', <new settings>)
>>    sys.stdout = open(sys.stdout.fileno(), 'w', <new settings>)
>>    sys.stderr = open(sys.stderr.fileno(), 'w', <new settings>)
>> Ditto for the other standard streams. It seems it already *is* as
>> simple as with any other file, we just collectively forgot about:
> One minor point - if sys.stdout is redirected, *and* you have already
> written to sys.stdout, this resets the file pointer. With test.py as
> import sys
> print("Hello!")
> sys.stdout = open(sys.stdout.fileno(), 'w', encoding='utf-8')
> print("Hello!")
> test.py >a gives one line in a, not two (tested on Windows, Unix may
> be different). And changing to "a" doesn't resolve this...

Ignore me - you need to flush stdout before repoening it, is all. Dumb
mistake, sorry for the noise :-(


More information about the Python-ideas mailing list