首页 > 解决方案 > 在 Juptyer 实验室/笔记本中突出显示检查函数的源代码

问题描述

在使用 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 实验室/笔记本中的快捷方式/热键在功能上使用它?

标签: pythonhtmljupyterinspectpygments

解决方案


This answer to this question建议添加以下display调用来插入样式:

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

推荐阅读