【问题标题】:iPython Notebook - Display source code for bash script with syntax highlightingiPython Notebook - 显示带有语法突出显示的 bash 脚本的源代码
【发布时间】:2014-11-09 01:07:06
【问题描述】:

如何在 iPython notebook 中显示带有语法高亮的 bash 脚本内容?

我的工作流程通常包括调用不同的 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

【问题讨论】:

    标签: bash syntax-highlighting ipython-notebook


    【解决方案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') 应该会得到所需的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2013-02-09
      • 2011-03-16
      • 1970-01-01
      • 2016-08-12
      相关资源
      最近更新 更多