Smarter way to do this? Unicode + stdin, stdout

B

BenjaMinster

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.
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

BenjaMinster said:
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:

What operating system are you using? Why do you want to do this?
Python attempts to determine the encoding of your terminal (if
sys.stdout is a terminal), and set sys.stdout.encoding accordingly.

Regards,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top