python - 在 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 实验室/笔记本中的快捷方式/热键在功能上使用它?
解决方案
This answer to this question建议添加以下display
调用来插入样式:
display(HTML("""
<style>
{pygments_css}
</style>
""".format(pygments_css=HtmlFormatter().get_style_defs('.highlight'))))
推荐阅读
- r - 如何更新 r 中列的值而不替换它
- sql-server - 意外令牌“UpdateOptions.ExpandFull”
- java - Java 2D 数组无法将值写入最后一个值索引
- angular - 如何以角度4导出为pdf
- python - 在 keras 模型中使用带有 dropout 的 Native tensorflow RNNLayer
- java - 旅行计划算法的图结构
- java - 未来
当可运行对象抛出异常时,.get() 卡住了——在单独的执行程序服务上运行时? - python - python cv2.imread,标志 cv2.IMREAD_COLOR 和 CV2.IMREAD_ANYCOLOR 有什么区别?
- .net - 将 VB.NET 项目移动到新计算机后日期无法正常工作
- c# - 图像未获得类 ID - Xamarin Forms