Can't print Chinese to HTTP

"Martin v. Löwis" martin at v.loewis.de
Mon Nov 30 07:53:13 EST 2009


Gnarlodious wrote:
> Hello. The "upgrade to Python 3.1 has been  disaster so far. I can't
> figure out how to print Chinese to a browser. If my script is:
> 
> #!/usr/bin/python
> print("Content-type:text/html\n\n")
> print('晉')
> 
> the Chinese string simply does not print. It works in interactive
> Terminal no problem, and also works in Python 2.6 (which my server is
> still running) in 4 different browsers. What am I doing wrong? BTW
> searched Google for 2 days no solution, if this doesn't get solved
> soon I will have to roll back to 2.6.
> 
> Thanks for any clue.

In the CGI case, Python cannot figure out what encoding to use for
output, so it raises an exception. This exception should show up in
the error log of your web server, please check.

One way of working around this problem is to encode the output
explicitly:

#!/usr/bin/python
print("Content-type:text/plain;charset=utf-8\n\n")
sys.stdout.buffer.write('晉\n'.encode("utf-8"))

FWIW, the Content-type in your example is wrong in two ways:
what you produce is not HTML, and the charset parameter is
missing.

Regards,
Martin



More information about the Python-list mailing list