Can't print Chinese to HTTP

D

Dave Angel

Gnarlodious said:
Because of the switch to unicode str, a simple print('晉') should've
worked flawlessly if your terminal can accept the character, but the
problem is your terminal does not.

There is nothing wrong with Terminal, Mac OSX supports Unicode from
one end to the other.
The problem is that your code works normally in Terminal but not in a
browser.

#!/usr/bin/python
import sys, io
print("Content-type:text/plain;charset=f-8\n\n")
sys.stdout =o.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
print("晉")

The browser shows "Server error", Apache 2 reports error:

[error] [client 127.0.0.1] malformed header from script. Bad header\xe6\x99\x89: test.py

So far every way to print Unicode to a browser looks very un-Pythonic.
I am just wondering if I have a bug or am missing the right way
entirely.

-- Gnarlie
You change the meaning of sys.stdout without flushing the previous
instance. So of course buffering can mess you up. If you want to
change the encoding, do it at the beginning of the script.

#!/usr/bin/python
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
print("Content-type:text/plain;charset=f-8\n\n")
print("晉")


(You probably could use sys.stdout.flush() before reassigning, but doing
it at the beginning is better for several reasons.)

DaveA
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top