Mercurial > hg > TextShaper
diff textshaper/indent.py @ 24:0930c6884f8a
STUB: README.txt setup.py textshaper/indent.py
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sun, 23 Feb 2014 10:57:19 -0800 |
parents | 0d0db0d79bfd |
children | c23782a7b7ba |
line wrap: on
line diff
--- a/textshaper/indent.py Sun Feb 23 10:14:06 2014 -0800 +++ b/textshaper/indent.py Sun Feb 23 10:57:19 2014 -0800 @@ -4,7 +4,7 @@ indentation of text blocks """ -import optparse +import argparse import os import sys @@ -42,33 +42,32 @@ return retval +def add_arguments(parser): + parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), + default=sys.stdin) + parser.add_argument('-o', '--output', dest='output', + help="output file or stdout if not given") + def main(args=sys.argv[1:]): - # TODO : refactor to be more general and stuff # parse command line - usage = '%prog [options] [file] [file2] [...]' description = """indent files or stdin if no files given""" - parser = optparse.OptionParser(usage=usage, description=__doc__) - parser.add_option('-o', '--output', dest='output', - help="output file or stdout if not given") - options, files = parser.parse_args(args) - - # input from files or stdin - if files: - missing = [not os.path.exists(filename) for filename in files] - if missing: - parser.error("File(s) not found: %s" % ', '.join(missing)) - def _files(): - for filename in files: - with open(f, 'r') as f: - yield f - else: - def _files(): - yield sys.stdin + parser = argparse.Argument(description=__doc__) + add_arguments(parser) + options = parser.parse_args(args) # process input for f in _files(): - print f + + # indent the text + indented = indent(f) + + # append to output + if options.output: + with open(options.output, 'a') as f: + f.write(indented) + else: + sys.stdout.write(indented) if __name__ == '__main__': main()