What is the best way to print the usage string ?

Bruno Desthuilliers onurb at xiludom.gro
Thu Aug 3 13:35:25 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:])
> 
> Notice that the string messes the indentation in my script. The
> indentation is correct, and if the script is invoked without
> arguments, the usage string is printed correctly.
> 
> Now, how can I achieve the same result while keeping a clean
> indentation ? How is this done in python world ? In C, I would do
> this:
> 
> ;; This buffer is for notes you don't want to save, and for Lisp
> evaluation.
> ;; If you want to create a file, visit that file with C-x C-f,
> ;; then enter the text in that file's own buffer.
> 
> if (argc < N) {
>    printf("Usage: blah blah blah\n"
>            "Some more lines in the usage text\n"
>            "Some more lines here too\n");
>    exit(1);
> }
> 
> The whitespace at the beginning of the string helps me keep the
> indentation clean, and the construct "a" "b" is syntactic sugar that
> allows me to create a large string without concatenating them at
> runtime.
> 
> How can I get this in Python ?

Quite close:

>>> args = []
>>> if not args:
...     print "line 1\n" \
...             "line 2\n" \
...             "line 3\n" \
...
...
line 1
line 2
line 3

But this is somehow ugly... the textwrapper module may be a better
solution. Or if you don't plan on making the script a module, you could
use the docstring:

bruno at bousin ~ $ cat ~/playground/concat.py
# !/usr/bin/python
"""
Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints \"a:b:c/\
"""

import sys
args = sys.argv[1:]
if not args:
  sys.exit(globals()['__doc__'].strip())
print reduce(lambda x, y: x + ':' + y, args)

bruno at bousin ~ $ python ~/playground/concat.py
Concat: concatenates the arguments with a colon (:) between
them
Usage: concat arg1 [arg2...]
Example: concat a b c prints "a:b:c/
bruno at bousin ~ $ python ~/playground/concat.py a b c
a:b:c
bruno at bousin ~ $




-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list