Last active
April 7, 2016 05:38
-
-
Save nojima/4c59a3f1a7356a2762867f25c79924b7 to your computer and use it in GitHub Desktop.
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/python [18/651] | |
''' | |
Pretty printer of LTSV. | |
How to use: | |
$ alias ltsvless='LESSOPEN="||=/path/to/ltsvpipe %s" less' | |
$ ltsvless /path/to/something.ltsv | |
''' | |
import sys | |
def code_to_chars(code): | |
return '\033[' + str(code) + 'm' | |
class Fore: | |
BLACK = code_to_chars(30) | |
RED = code_to_chars(31) | |
GREEN = code_to_chars(32) | |
YELLOW = code_to_chars(33) | |
BLUE = code_to_chars(34) | |
MAGENTA = code_to_chars(35) | |
CYAN = code_to_chars(36) | |
WHITE = code_to_chars(37) | |
RESET = code_to_chars(39) | |
class Back: | |
BLACK = code_to_chars(40) | |
RED = code_to_chars(41) | |
GREEN = code_to_chars(42) | |
YELLOW = code_to_chars(43) | |
BLUE = code_to_chars(44) | |
MAGENTA = code_to_chars(45) | |
CYAN = code_to_chars(46) | |
WHITE = code_to_chars(47) | |
RESET = code_to_chars(49) | |
class Style: | |
BRIGHT = code_to_chars(1) | |
DIM = code_to_chars(2) | |
NORMAL = code_to_chars(22) | |
RESET_ALL = code_to_chars(0) | |
def main(): | |
if len(sys.argv) < 2: | |
sys.stderr.write('Usage: ltsvpipe FILENAME\n') | |
sys.exit(2) | |
filename = sys.argv[1] | |
with open(filename) as f: | |
for line in f: | |
line = line.rstrip('\n') | |
columns = line.split("\t") | |
for i, c in enumerate(columns): | |
kv = c.split(':', 1) | |
if len(kv) < 2: | |
key = kv[0] | |
value = '' | |
else: | |
key = kv[0] | |
value = kv[1] | |
sys.stdout.write( | |
Fore.YELLOW + Style.BRIGHT + key + | |
Style.RESET_ALL + Fore.GREEN + '="' + | |
Fore.GREEN + value + | |
Fore.GREEN + '"' + | |
Fore.RESET) | |
if i == len(columns) - 1: | |
sys.stdout.write('\n') | |
else: | |
sys.stdout.write(' ') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment