what is best method to set sys.stdout to utf-8?

P

Peter Kleiweg

In Python 3, there seem to be two ways to set sys.stdout to
utf-8 after the script has started:

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')

I guess the second is better. At start-up, type(sys.stdout) is
<class '_io.TextIOWrapper'>, and it's also after using the
second method.

After using the first method, type(sys.stdout) is changed to
<class 'encodings.utf_8.StreamWriter'>.

Should I always use the second method?
 
T

Terry Reedy

In Python 3, there seem to be two ways to set sys.stdout to
utf-8 after the script has started:

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')

I guess the second is better. At start-up, type(sys.stdout) is
<class '_io.TextIOWrapper'>, and it's also after using the
second method.

After using the first method, type(sys.stdout) is changed to
<class 'encodings.utf_8.StreamWriter'>.

Should I always use the second method?

I would. The io module is more recent an partly replaces codecs. The
latter remains for back compatibility and whatever it can do that io cannot.
 
L

Laurent Claessens

I would. The io module is more recent an partly replaces codecs. The
latter remains for back compatibility and whatever it can do that io cannot.


I've a naive question : what is wrong with the following system ?

class MyStdOut(object):
def __init__(self):
self.old_stdout=sys.stdout
def write(self,x):
try:
if isinstance(x,unicode):
x=x.encode("utf8")
except (UnicodeEncodeError,UnicodeDecodeError):
sys.stderr.write("This should not happen !")
raise
self.old_stdout.write(x)
sys.stdout=MyStdOut()


.... well ... a part of the fact that it is much longer ?


Laurent Claessens
 
L

Laurent Claessens

I would. The io module is more recent an partly replaces codecs. The
latter remains for back compatibility and whatever it can do that io cannot.


I've a naive question : what is wrong with the following system ?

class MyStdOut(object):
def __init__(self):
self.old_stdout=sys.stdout
def write(self,x):
try:
if isinstance(x,unicode):
x=x.encode("utf8")
except (UnicodeEncodeError,UnicodeDecodeError):
sys.stderr.write("This should not happen !")
raise
self.old_stdout.write(x)
sys.stdout=MyStdOut()


.... well ... a part of the fact that it is much longer ?


Laurent Claessens
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top