pygments

Send to Kindle
home » snippets » python » pygments


Sample usage

Highlight a python file and display on the terminal

print pygments.highlight(
        open("/Users/chirayu/tmp/differ.py").read(),
        pygments.lexers.get_lexer_by_name("python"),
        pygments.formatters.get_formatter_by_name("terminal256", style="emacs"))

List available formatters and lexers

pprint.pprint(list(pygments.formatters.get_all_formatters()))

pprint.pprint(list(pygments.lexers.get_all_formatters()))

Get a lexer for a specific filename

try:
    lexer = pygments.lexers.get_lexer_for_filename("/Users/chirayu/tmp/differ.py")
    print "Lexer is", lexer
except ValueError:
    print "Couldn't locate a lexer"