add columnized output

This commit is contained in:
nebukadnezzar 2013-08-12 02:15:35 +02:00
parent 824e3dd99c
commit eed51ae5de
1 changed files with 37 additions and 23 deletions

60
cheat
View File

@ -1,32 +1,46 @@
#!/usr/bin/env python #!/usr/bin/env python
import os import os
import sys import sys
from itertools import izip_longest, islice
# assemble a keyphrase out of all params passed to the script def columnize(sequence, columns=2):
keyphrase = ' '.join(sys.argv[1:]) size, remainder = divmod(len(sequence), columns)
cheat_dir = os.path.expanduser('~') + '/.cheat/' if remainder:
size += 1
slices = [islice(sequence, pos, pos + size)
for pos in xrange(0, len(sequence), size)]
return izip_longest(fillvalue='', *slices)
# verify that the ~/.cheat directory exists def main():
if not os.path.isdir(cheat_dir): # assemble a keyphrase out of all params passed to the script
print >> sys.stderr, 'The ~/.cheat directory does not exist.' keyphrase = ' '.join(sys.argv[1:])
exit() cheat_dir = os.path.expanduser('~') + '/.cheat/'
# list the files in the ~/.cheat directory # verify that the ~/.cheat directory exists
cheatsheets = os.listdir(cheat_dir) if not os.path.isdir(cheat_dir):
cheatsheets.sort() sys.stderr.write('The ~/.cheat directory does not exist.')
exit()
# print help if requested # list the files in the ~/.cheat directory
if keyphrase in ['', 'help', '--help', '-h']: cheatsheets = os.listdir(cheat_dir)
print "Usage: cheat [keyphrase]\n" cheatsheets.sort()
print "Available keyphrases:"
print "\n".join(cheatsheets)
exit()
# print the cheatsheet if it exists # print help if requested
if keyphrase in cheatsheets: if keyphrase in ['', 'help', '--help', '-h']:
with open (cheat_dir + keyphrase, 'r') as cheatsheet: print("Usage: cheat [keyphrase]\n")
print cheatsheet.read() print("Available keyphrases:")
for values in columnize(cheatsheets, 4):
print(" %s" % ' '.join(value.ljust(20) for value in values))
exit()
# if it does not, say so # print the cheatsheet if it exists
else: if keyphrase in cheatsheets:
print 'No cheatsheet found.' with open (cheat_dir + keyphrase, 'r') as cheatsheet:
print(cheatsheet.read())
# if it does not, say so
else:
print('No cheatsheet found.')
if __name__ == '__main__':
main()