On 9 June 2012 12:00, Paul Moore <p.f.moore@gmail.com> wrote:
On 9 June 2012 10:55, Nick Coghlan <ncoghlan@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 :-( Paul.