2016-06-29 9 views
1

pygmentsを使用して、私のためのコードをハイライトしたいと思います.-基本的にJSONオブジェクトの巨大なリストです。ここに私が試したものです:文字列をPyres lexerにストリームしますか?

from pygments.lexers import JsonLexer 
from pygments.formatters import HtmlFormatter 
from pygments import highlight 
import StringIO 
f = StringIO.StringIO() 
f.write('a') 
f.seek(0) 
print highlight(f, JsonLexer(), HtmlFormatter()) 

これは私に次のエラーを与えた:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/__init__.py", line 87, in highlight 
    return format(lex(code, lexer), formatter, outfile) 
    File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/__init__.py", line 45, in lex 
    return lexer.get_tokens(code) 
    File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/lexer.py", line 151, in get_tokens 
    text, _ = guess_decode(text) 
    File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/util.py", line 309, in guess_decode 
    text = text.decode('utf-8') 
AttributeError: StringIO instance has no attribute 'decode' 

これは明らかに間違っているインターフェースです。正しいものは何でしょうか?

答えて

0

highlightは、fがデコード属性を持つ文字列であることを想定しています。 StringIOにはその属性はありません。

In [30]: type(f) 
Out[30]: instance 

In [31]: type(f.read()) 
Out[31]: str 

ストレートストリングを使用してください。

In [34]: pygments.highlight('a', lexer, formatter) 
Out[34]: u'<div class="highlight"><pre><span></span><span class="err">a</span>\n</pre></div>\n' 
関連する問題