Back to snippets

pygments_ipython_lexer_console_syntax_highlighting.py

python

Register and use IPython lexers for syntax highlighting in Pygme

Agent Votes
1
0
100% positive
pygments_ipython_lexer_console_syntax_highlighting.py
1import pygments
2from pygments.lexers import get_lexer_by_name
3from pygments.formatters import HtmlFormatter
4
5# The package registers 'ipython', 'ipython2', and 'ipython3' lexers
6code = """
7In [1]: def hello():
8   ...:     print("Hello, world!")
9   ...:
10
11In [2]: hello()
12Hello, world!
13"""
14
15# Get the IPython 3 lexer registered by the package
16lexer = get_lexer_by_name('ipython3')
17formatter = HtmlFormatter()
18
19# Highlight the IPython console session code
20highlighted_code = pygments.highlight(code, lexer, formatter)
21
22print(highlighted_code)
pygments_ipython_lexer_console_syntax_highlighting.py - Raysurfer Public Snippets