且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python编程:使用pygments高亮代码

更新时间:2022-09-07 21:11:27

参考文档:http://pygments.org/

安装

python环境 : python3

Pygments版本:2.2.0

pip install Pygments

命令行使用

第一步: 准备代码

# -*- coding: utf-8 -*-

# @Date    : 2018-10-17
# @Author  : Peng Shiyu

def hello():
    print("hello world!")


if __name__ == '__main__':
    hello()

第二步:生成html

$ pygmentize -f html -o hello.html hello.py

参数:

-f html 指明需要输出html文件

-o hello.html 指明输出的文件名

hello.py 就是输入文件了

第三步:生成css

$ pygmentize -f html -a .highlight -S default > highlight.css

-a .highlight指所有css选择器都具有.highlight这一祖先选择器

-S default就是指定所需要的样式了,各位可以对各种样式都尝试一下。在官网上是可以直接尝试的哦!

> pygments.css将内容输出到pygments.css文件中

第四步:引用css文件

hello.html文件中引用css文件

<link rel="stylesheet" href="highlight.css">

浏览器中打开hello.html的最终效果:

Python编程:使用pygments高亮代码

代码中使用

刚开始查看官方文档,代码复制下来不能用,又自己研究了一下

# -*- coding: utf-8 -*-

# @Date    : 2018-10-17
# @Author  : Peng Shiyu

from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from pygments.lexers.python import PythonLexer

code = 'print("hello world")'

# 二选一即可
# lexer = PythonLexer()
lexer = get_lexer_by_name("python")

# 指定风格
formatter = HtmlFormatter(style="xcode")

# 获取html
html = highlight(code, lexer, formatter)

print(html)
"""
<div class="highlight">
    <pre>
        <span></span>
        <span class="k">print</span>
        <span class="p">(</span>
        <span class="s2">&quot;hello world&quot;</span>
        <span class="p">)</span>
        </pre>
</div>
"""

# 获取css
css = formatter.get_style_defs('.highlight')

print(css)
"""
.highlight .hll { background-color: #ffffcc }
.highlight  { background: #ffffff; }
.highlight .c { color: #177500 } /* Comment */
.highlight .err { color: #000000 } /* Error */
...
"""

将所输出的文本分别存入html、css文件,并在html中对css文件引用(如命令行中使用),最后也就呈现了一样的效果(需要将code变量换为命令行中使用的待格式化代码)

查看支持的风格


from pygments.styles import STYLE_MAP

for key in STYLE_MAP.keys():
    print(key)
    
"""    
default
emacs
friendly
colorful
autumn
murphy
manni
monokai
perldoc
pastie
borland
trac
native
fruity
bw
vim
vs
tango
rrt
xcode
igor
paraiso-light
paraiso-dark
lovelace
algol
algol_nu
arduino
rainbow_dash
abap
"""

以上风格带入HtmlFormatter中就能更改

参考文章

  1. Pygments Introduction and Quickstart
  2. 使用Pygments来实现代码高亮