3

Python 2.6.6 を実行しています。

猫tbuild.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

from mako.template import Template

_template="""
% for v in my_list:
  ${'abc'.encode('utf-8')}
  ${'風連町?'.encode('utf-8')}
% endfor
"""


print Template(_template).render_unicode(my_list = [1, 2],
                                         input_encoding='utf-8',
                                         output_encoding='utf-8',
                                         encoding_errors='replace'
                                        )

./tbuild.py gives.
  File "./tbuild.py", 
  line 15, in <module> print Template(_template).render_unicode(my_list = [1, 2],
  File "/usr/lib/python2.6/site-packages/mako/template.py", 
  line 91, in __init__ (code, module) = _compile_text(self, text, filename)
  File "/usr/lib/python2.6/site-packages/mako/template.py", 
  line 357, in _compile_text node = lexer.parse()
  File "/usr/lib/python2.6/site-packages/mako/lexer.py", 
  line 192, in parse self.filename,)
  File "/usr/lib/python2.6/site-packages/mako/lexer.py", 
  line 184, in decode_raw_stream 0, 0, filename)
  mako.exceptions.CompileException: Unicode decode operation of 
  encoding 'ascii' failed at line: 0 char: 0

日本語の行を削除すると、正常に動作します。私が理解していない基本的なことが明らかにあります。

助けてくれてありがとう、eo

4

1 に答える 1

2

I would be surprised even if ${'á'.encode('utf-8')} worked. You need to specify unicode strings as such, using the unicode literal u. Rewrite ${'風連町?'.encode('utf-8')} as ${u'風連町?'.encode('utf-8')} and do the same for any text that you are handling.

EDIT:

Taking mako into consideration:

# -*- coding: utf-8 -*-

from mako.template import Template

_template=u"${u'風連町?'}"
x = Template(_template, output_encoding='utf-8')
print x.render()

The output_encoding parameter makes sense when creating a Template, it has no meaning in the render method. Also, why would you encode input, decode input using same encoding, and then use render_unicode ? In fact, render_unicode ignores output_encoding, so it seems you actually want to use render.

于 2012-12-06T04:17:39.753 に答える