Skip to content

Instantly share code, notes, and snippets.

@tilboerner
Last active January 31, 2017 16:54
Show Gist options
  • Save tilboerner/fd86afc63927e42b46dd521b402e6a28 to your computer and use it in GitHub Desktop.
Save tilboerner/fd86afc63927e42b46dd521b402e6a28 to your computer and use it in GitHub Desktop.
The Tao of Unix Programming
#! /usr/bin/python3
""" The tao of unix programming, Python-adapted from github:globalcitizen/taoup
Quotes via:
https://raw.githubusercontent.com/globalcitizen/taoup/master/taoup
"""
import itertools
import os
import random
import re
import shutil
import sys
import textwrap
TAOFILE = os.path.expanduser('~/taoup.txt')
def wrap(txt):
global _wrapper
width, height = shutil.get_terminal_size((80, 20))
try:
_wrapper.width = width
except NameError:
_wrapper = textwrap.TextWrapper(width=width)
return '\n'.join(_wrapper.wrap(txt))
# # s <-- https://raw.githubusercontent.com/globalcitizen/taoup/master/taoup
# parts = re.compile('''(?<=")[^{}"]+?(?=")|(?<=')[^{}']+?(?=')''')
# for line in s.splitlines():
# if not line.strip().startswith('puts'):
# continue
# quote = ''.join(parts.findall(line))
# if quote.strip():
# q.append(quote)
# with open(TAOFILE, 'w') as taofile:
# for quote in q:
# print(quote, file=taofile)
def random_item(iterable):
# http://nedbatchelder.com/blog/201208/selecting_randomly_from_an_unknown_sequence.html
# http://stackoverflow.com/questions/12128948/python-random-lines-from-subfolders/12134726#12134726
choice = None
for i, item in enumerate(iterable):
if random.randint(0, i) == 0:
choice = item
return choice
def yield_quotes(path):
with open(path) as infile:
yield from (line for line in infile if line.strip())
def all(lines, jump=None):
"""print all non-blank lines in file, waiting for enter after each one"""
count = 0
for line in lines:
if jump and jump(line):
print('\n', wrap(line))
else:
count += 1
print(wrap('({:,}) {}'.format(count, line)))
input()
def usage(script):
print('''{script} [random|all]
The Tao of Unix Programming, lines from https://github.com/globalcitizen/taoup/
'''.format(script=script))
def main(script='taoup', mode=None):
mode = mode or 'random'
is_header = lambda line: line.startswith('-----')
quotes = yield_quotes(TAOFILE)
try:
if mode == 'random':
quote = random_item(quote for quote in quotes if not is_header(quote))
if quote:
print(quote)
elif mode == 'all':
all(quotes, jump=is_header)
print('Done, thank you!')
else:
usage(script)
exit(0 if mode in {'-h', '--help'} else 1)
except KeyboardInterrupt:
if mode == 'all':
print('\b\b', end='') # erase "^C" from terminal
print('Okay, bye.')
if __name__ == '__main__':
script, *args = sys.argv
*_, script = os.path.split(script)
main(script, *args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment