在Juptyer实验室/笔记本中突出显示受检查功能的源代码

时间:2019-05-01 08:05:51

标签: python html jupyter inspect pygments

在使用Jupyter实验室/笔记本时,我一直在使用以下函数检查函数源代码:

def source(function):
    print(inspect.getsource(function))

对于较短的代码,这很好,但是在某些时候,突出显示代码会很方便。因此,我开始研究使用Pygments:

def source2(function):
    from IPython.core.display import HTML, display
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import HtmlFormatter
    code = inspect.getsource(function)
    html = highlight(code, PythonLexer(), HtmlFormatter(style='colorful'))
    display(HTML(html))

虽然这似乎会产生中间的HTML代码并正确显示它,但代码保持原样(不突出显示)。中间字符串变量“ html”具有以下内容。

'<div class="highlight">
 <pre><span>
 </span><span class="k">def</span>
 <span class="nf">source</span>
 <span class="p">(</span>
 <span class="n">function</span>
 <span class="p">):</span>\n
 <span class="k">print</span>
 <span class="p">(</span>
 <span class="n">inspect</span>
 <span class="o">.</span>
 <span class="n">getsource</span>
 <span class="p">(</span>
 <span class="n">function</span>
 <span class="p">))</span>\n
 </pre></div>\n'

我相信我可能只是缺少CSS文件?

奖金问题(稍后可能会解决):是否可以通过右键单击上下文菜单或Jupyter实验室/笔记本中的快捷键/热键在函数上使用此功能?

1 个答案:

答案 0 :(得分:0)

this question的回答建议添加以下display调用以插入样式:

display(HTML("""
<style>
{pygments_css}
</style>
""".format(pygments_css=HtmlFormatter().get_style_defs('.highlight'))))
相关问题