#! /usr/bin/env python3 from __future__ import print_function import sys def usage(code=0): sys.stderr.write("Usage: %s [-0|--null] [-n|--no-newline] [-s|--space] [-w|--width] [width]\n" % sys.argv[0]) sys.exit(code) def get_args(): from getopt import getopt, GetoptError try: options, arguments = getopt( sys.argv[1:], "0nsw:", ["null", "no-newline", "space", "width="]) except GetoptError: usage(1) print0 = False newline = True space = '' width = None for option, value in options: if option in ("-h", "--help"): usage() elif option in ("-0", "--null"): print0 = True elif option in ("-n", "--no-newline"): newline = False elif option in ("-s", "--space"): space = u' ' elif option in ("-w", "--width"): width = int(value) else: usage(2) if arguments: if width is not None: usage(3) elif len(arguments) > 1: usage(4) else: width = int(arguments[0]) return print0, newline, space, width print0, newline, space, width = get_args() text = sys.stdin.read() if not newline: text = text.rstrip() if width: import textwrap text = textwrap.fill( text, width - 2*len(space), initial_indent=space, subsequent_indent=space) if space: text = u'\n'.join([line+space for line in text.split(u'\n')]) else: text = u"%s%s%s" % (space, text, space) sys.stdout.write(text) if print0: sys.stdout.write('\0') elif newline: print()