What is the best way to print the usage string ?
Steven Bethard
steven.bethard at gmail.com
Thu Aug 3 13:36:45 EDT 2006
Leonel Gayard wrote:
> Hi all,
>
> I had to write a small script, and I did it in python instead of
> shell-script. My script takes some arguments from the command line,
> like this.
>
> import sys
> args = sys.argv[1:]
> if args == []:
> print """Concat: concatenates the arguments with a colon (:) between
> them
> Usage: concat arg1 [arg2...]
> Example: concat a b c prints \"a.jar:b.jar:c/\""""
> sys.exit(1)
> print reduce(lambda x, y: x + ':' + y, sys.argv[1:])
The short answer is to use textwrap.dedent::
>>> import textwrap
>>> if True:
... print textwrap.dedent('''\
... Concat: concatenates the arguments with a colon (:) between
... them
... Usage: concat arg1 [arg2...]
... Example: concat a b c prints "a.jar:b.jar:c/"''')
...
Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints "a.jar:b.jar:c/"
You also might consider using an argument parsing like argparse[1] to
build your usage string for you:
------------------------------ concat.py ------------------------------
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='concatenates the arguments with a colon (:) '
'between them')
parser.add_argument('args', metavar='arg', nargs='+',
help='one item to be concatenated')
namespace = parser.parse_args()
print ':'.join(namespace.args)
-----------------------------------------------------------------------
$ concat.py
usage: concat.py [-h] arg [arg ...]
concat.py: error: too few arguments
$ concat.py -h
usage: concat.py [-h] arg [arg ...]
concatenates the arguments with a colon (:) between them
positional arguments:
arg one item to be concatenated
optional arguments:
-h, --help show this help message and exit
$ concat.py a b c
Steve
[1] http://argparse.python-hosting.com/
More information about the Python-list
mailing list