apache - Python 3.4 causes UnicodeEncodeError on Apache2 server (Mac) but works fine in command line -


i'm trying python 3.4 cgi script , apache output 'ü' character in browser (same problem occurs other unicode character, matter). python 3.4 cgi script causes unicodeencodeerror in apache while similar python 2.7 code works fine on same server. both scripts 3.4 , 2.7 work fine command line.

this error while running python 3.4 script:

unicodeencodeerror: 'ascii' codec can't encode character '\xfc' in position 23: ordinal not in range(128)

here's code causes error:

#!/usr/local/bin/python3 # -*- coding: utf-8 -*-  print ("content-type: text/html; charset=utf-8\n\n") print ("""\ <html> <head> <meta charset="utf-8"> </head> <body> """)  print ("u umlaut (python 3.4): ü<br>")  print ("""\ </body> </html> """) 

the python 2.7 script below on same server displays ü , other unicode characters correctly: (so it's not apache problem?)

#!/usr/bin/python # -*- coding: utf-8 -*-  print "content-type: text/html; charset=utf-8\n\n" print """\ <html> <head> <meta charset="utf-8"> </head> <body> """  print "u umlaut (python 2.7): ü<br>"  print """\ </body> </html> """ 

both scripts work correctly command line. have

adddefaultcharset utf-8 

in httpd.conf.

also, locale variables set follows:

lang="en_us.utf-8" lc_collate="en_us.utf-8" lc_ctype="en_us.utf-8" lc_messages="en_us.utf-8" lc_monetary="en_us.utf-8" lc_numeric="en_us.utf-8" lc_time="en_us.utf-8" lc_all="en_us.utf-8" 

a included utf-8 setting everywhere think of (sometimes excessively). know else can python 3.4 script display unicode characters correctly in browser? thanks.

i know few moons since question stumbled on facing same problem. , found solution. maybe not other seekers.

jack o'connor's solution fixed problem me try this:

import sys sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1) print("日本語") # works other methods of writing stdout: sys.stdout.write("日本語\n") sys.stdout.buffer.write("日本語\n".encode())` 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -