When running Python CGI with Lolipop Apparently, even if I write Japanese in the print statement normally, an error occurs and it cannot be displayed.
It seems that the standard output is treated as a pipe and the encoding specification is ignored.
wk.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, locale, codecs
print "Content-Type: text/html\n\n"
print 'sys.stdin.encoding: %s\n\n' % sys.stdin.encoding
print 'sys.stdout.encoding: %s\n\n' % sys.stdout.encoding
print '%s\n\n' % sys.getfilesystemencoding()
print '%s\n\n' % sys.getdefaultencoding()
print '%s\n\n' % sys.stdin.encoding
print '%s\n\n' % sys.stdout.encoding
print '%s\n\n' % sys.stderr.encoding
Will produce the following results.
sys.stdin.encoding: None
sys.stdout.encoding: None
ANSI_X3.4-1968
ascii
None
None
None
Forcibly use encoding to change the output destination of the print statement.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, locale, codecs
print "Content-Type: text/html\n\n"
wk = u"Display Japanese"
Writer = codecs.getwriter('utf-8')
stdout = Writer(sys.stdout)
print >>stdout, u"%s" % (wk)
As a result, the following line is displayed.
Display Japanese
Recommended Posts