Search code examples
jupyter-notebookipythonsyntax-highlighting

Script display from an external file in Jupyter Notebook with syntax-highlighting


I am making a tutorial using Jupyter and I would like to display the content of an external Python script. Printing the content of the file is trivial, but I am interested in a color-coded/syntax-highlighted text (either in a markdown cell or as an output).


Solution

  • Use Ipython's Markdown module:

    from IPython.display import Markdown as md
    
    script = """
    x = 2
    if x*2 > 2:
        print('x > 2')
    else:
        x = None
    """
    
    md("```Python" + script + "```")
    

    Will output:

    enter image description here