将字符串串流为pygments lexer?

时间:2016-06-29 15:11:35

标签: python json streaming syntax-highlighting pygments

我想使用pygments为我突出显示代码 - 基本上是一个巨大的JSON对象列表。这是我试过的:

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'

显然这是错误的界面。什么是正确的?

1 个答案:

答案 0 :(得分:0)

highlight要求f为字符串,它具有decode属性。 StringIO没有该属性。

atexit

只需使用直线。

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

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