-
-
Save natural/dd5d3e5102663e589c404106fd95c57e to your computer and use it in GitHub Desktop.
page count
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 argparse import ArgumentParser, ArgumentTypeError | |
from subprocess import check_output | |
from sys import exit, stdout | |
def format_count(count, scale): | |
return f'%.{scale}f' % count | |
def format_line(count, filename): | |
return '{:>8} {}'.format(count, filename) | |
def mk_min_arg(prefix, type, min): | |
def min_arg(value): | |
value = type(value) | |
if value < min: | |
raise ArgumentTypeError(f'{prefix} value must be {min} or greater.') | |
return value | |
return min_arg | |
def parse_args(): | |
parser = ArgumentParser() | |
parser.add_argument( | |
'filenames', | |
nargs='*', | |
default=['-'], | |
help='file names or none for stdin' | |
) | |
parser.add_argument( | |
'--size', | |
default=300, | |
type=mk_min_arg('size', int, min=1), | |
help='size of page, 1 or greater, default=300' | |
) | |
parser.add_argument( | |
'--scale', | |
default=1, | |
type=mk_min_arg('scale', int, min=0), | |
help='decimal scale, 0 or greater, default=1' | |
) | |
return parser.parse_args() | |
def output_line(value, scale, name, file=None): | |
file = stdout if file == None else file | |
print(format_line(format_count(value, scale), name), file=file) | |
def count_pages(filename, size, positive_size=mk_min_arg('size', int, min=1)): | |
output = check_output(f"wc -w {filename} | awk '{{print $1}}'", shell=True) | |
return float(output) / positive_size(size) | |
def count_pages_command(filenames, size, scale): | |
total = 0 | |
for filename in filenames: | |
pages = count_pages('' if filename == '-' else filename, size=size) | |
total += pages | |
output_line(pages, scale, '<stdin>' if filename == '-' else filename) | |
output_line(total, scale, 'total') | |
if __name__ == '__main__': | |
try: | |
count_pages_command(**parse_args().__dict__) | |
except (KeyboardInterrupt, ): | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment