Last active
May 15, 2017 18:33
-
-
Save sivel/6d16d5c054b5ba87ab2052fab53afc02 to your computer and use it in GitHub Desktop.
Python file that works similarly to cat, while performing (guessed) syntax highlighting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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