MichM MichM - 1 month ago 17
Python Question

python 2.7 how to change sys.displayhook back to default

For

a = u'\u4e00'
if I type
a
in the console, I get:
u'\u4e00'
. So to display
a
as the unicode character, I can change the sys.displayhook as follows:

import sys
def my_display(x):
if isinstance(x, unicode):
sys.stdout.write(x.encode("utf-8"))
else:
sys.stdout.write(repr(x))
sys.stdout.write("\n")

sys.displayhook = my_display


Then if I type
a
in the console I get
δΈ€
.

The question: if after that, I want to change the sys.displayhook back to the original default setting. How can I do that?

Answer
sys.displayhook = sys.__displayhook__

sys.__displayhook__ stores the original sys.displayhook for cases like this.

(By the way, I would also advise not doing your original sys.displayhook replacement. You probably just want print a, maybe with something to match the encoding to your terminal's encoding.)