pip install Pygments
python
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
python
style = 'tango'
python
lexer = get_lexer_by_name('python', stripall=True)
formatter = HtmlFormatter(style=style, full=True, cssclass='code')
python
code = '''
def greet():
print("Hello, world!")
greet()
'''
colored_code = highlight(code, lexer, formatter)
python
with open('colored_code.html', 'w') as f:
f.write('<html><head><style>{}</style></head><body>{}</body></html>'.format(HtmlFormatter().get_style_defs('.code'), colored_code))