Skip to content

Instantly share code, notes, and snippets.

@sivel
Last active May 15, 2017 18:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sivel/6d16d5c054b5ba87ab2052fab53afc02 to your computer and use it in GitHub Desktop.
Python file that works similarly to cat, while performing (guessed) syntax highlighting
#!/usr/bin/env python
from __future__ import print_function
import sys
from pygments import highlight
from pygments.lexers import guess_lexer
from pygments.formatters import Terminal256Formatter as Formatter
# Try to load the Solarized256Style
# https://github.com/johnmastro/solarized256-pygments
try:
from solarized256 import Solarized256Style as style
except ImportError:
style = 'default'
def main():
try:
if len(sys.argv) == 1:
text = sys.stdin.read()
elif len(sys.argv) == 2:
with open(sys.argv[1], 'rb') as f:
text = f.read()
else:
raise SystemExit(sys.argv[0] + " [infile]")
except Exception, e:
raise SystemExit(e)
try:
if sys.stdout.isatty():
print(
highlight(text, guess_lexer(text), Formatter(style=style)),
end=''
)
else:
print(text, end='')
except IOError:
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment