Smarter way to do this? Unicode + stdin, stdout

BenjaMinster benjaminster at gmail.com
Sat Dec 16 23:53:49 EST 2006


I want to read and write unicode on stdin and stdout.  I can't seem to
find any way to force sys.stdin.encoding and sys.stdout.encoding to be
utf-8, so I've got the following workaround:

import codecs, sys
out = codecs.getwriter("utf-8")(sys.stdout)

def tricky(): return sys.stdin.readline().decode("utf-8").[:-1]

That is, I wrap sys.stdout in a utf-8 writer and I read utf-8 input
from stdin as normal characters then convert it to
unicode and chop off the newline.  Wrapping stdin with
codecs.getreader() doesn't work for some reason--when I call readline()
on the resulting wrapped stream, it won't return until I send it Ctrl+d
twice!  Then stdin is closed which is of course not helpful.




More information about the Python-list mailing list