我的工作流程通常包括调用不同的bash脚本,我想在笔记本中记录这些脚本的源代码。我目前的解决方案是创建一个bash单元格并cat
脚本将其内容显示在单元格输出中。但是,脚本没有格式化,这也有点麻烦。
代码单元格:
%%bash
cat myScript.sh
输出:
#! /bin/bash
for i in {1..3}; do [ "$i" == "2" ] && echo "This is my bash script"; done
所需输出(带语法高亮显示):
#! /bin/bash
for i in {1..3}; do [ "$i" == "2" ] && echo "This is my bash script"; done
答案 0 :(得分:1)
您可以在similar fashion to this question中使用pygments。这是一个例子:
def highlight_source_bash(filename):
"""For use inside an IPython notebook: given a filename, print the source code. Bash version."""
from pygments import highlight
from pygments.lexers import BashLexer
from pygments.formatters import HtmlFormatter
from IPython.core.display import HTML
with open (filename, "r") as myfile:
data = myfile.read()
return HTML(highlight(data, BashLexer(), HtmlFormatter(full=True)))
然后调用highlight_source_bash('myScript.sh')
应该提供所需的输出。