Skip to content

Instantly share code, notes, and snippets.

@MLKrisJohnson
Created October 17, 2022 13:24
Show Gist options
  • Save MLKrisJohnson/7b1b2883459b44ada6996239f7b692c7 to your computer and use it in GitHub Desktop.
Save MLKrisJohnson/7b1b2883459b44ada6996239f7b692c7 to your computer and use it in GitHub Desktop.
Demonstration of Python standard library textwrap module.
#!/usr/bin/env python3
"""
Demonstration of Python standard library textwrap module.
Run "python3 wrap_test.py -h" for command-line options.
"""
import argparse
import sys
import textwrap
def parse_command_line():
"""Parse command line arguments, returning a namespace of argument values."""
argp = argparse.ArgumentParser(
description="Wraps text into lines of specified length",
epilog="See the documentation of the Python argparse module for more info."
)
argp.add_argument('filepath', nargs='*',
help="path to input file (default: standard input)"
)
argp.add_argument('-w', '--width',
type=int, metavar="N", default=70,
help="maximum length of wrapped lines (default: %(default)s)",
)
argp.add_argument('--max-lines', metavar="N", type=int, default=None,
help="if set, then the output will contain at most this many lines"
)
argp.add_argument('--placeholder', metavar="TEXT", default=" [...]",
help="string that will appear at end of output text if truncated (default: \"%(default)s\")"
)
argp.add_argument('--expand-tabs',
action=argparse.BooleanOptionalAction, default=True,
help="if true, all tab characters will be expanded to spaces"
)
argp.add_argument('--tabsize',
type=int, metavar="N", default='8',
help="number of spaces tabs are expanded to if --expand-tabs is set (default: %(default)s)"
)
argp.add_argument('--replace-whitespace',
action=argparse.BooleanOptionalAction, default=True,
help="after tab expansion, replace each whitespace character with a single space"
)
argp.add_argument('--drop-whitespace',
action=argparse.BooleanOptionalAction, default=True,
help=" if true, whitespace at the beginning and ending of every line is dropped"
)
argp.add_argument('--initial-indent',
metavar="TEXT", default='',
help="prefix for first line of wrapped output",
)
argp.add_argument('--subsequent-indent',
metavar="TEXT", default='',
help="prefix for all lines except the first"
)
argp.add_argument('--fix-sentence-endings',
action=argparse.BooleanOptionalAction, default=False,
help="if true, ensure sentences are always separated by two spaces"
)
argp.add_argument('--break-long-words',
action=argparse.BooleanOptionalAction, default=True,
help="if true, then words longer than --width will be broken"
)
argp.add_argument('--break-on-hyphens',
action=argparse.BooleanOptionalAction, default=True,
help="if true, wrap on whitespace and after hyphens in compound words"
)
return argp.parse_args()
def wrap_and_print(text, args):
"""Apply text-wrapping to the given text according to the command-line
options, then print the result.
"""
lines = textwrap.wrap(text,
width=args.width,
initial_indent=args.initial_indent,
subsequent_indent=args.subsequent_indent,
expand_tabs=args.expand_tabs,
tabsize=args.tabsize,
replace_whitespace=args.replace_whitespace,
fix_sentence_endings=args.fix_sentence_endings,
break_long_words=args.break_long_words,
break_on_hyphens=args.break_on_hyphens,
drop_whitespace=args.drop_whitespace,
max_lines=args.max_lines,
placeholder=args.placeholder,
)
for line in lines:
print(line)
def main():
"""Main entry point."""
args = parse_command_line()
if len(args.filepath) > 0:
# Process list of input files
for path in args.filepath:
with open(path, 'r') as f:
text = f.read()
wrap_and_print(text, args)
else:
# No filepaths given on command line, so read standard input
text = sys.stdin.read()
wrap_and_print(text, args)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment