What is the best way to print the usage string ?

Simon Forman rogue_pedro at yahoo.com
Thu Aug 3 13:21: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 ?
>
> []'s
> Leonel

Python also concatenates adjacent strings, but the "real" newlines
between your strings will need to be escaped (otherwise, because the
newlines are statement separators, you will have one print statement
followed by string literals with the wrong indentation.)

print "Usage: blah blah blah\n" \
      "Some more lines in the usage text\n" \
      "Some more lines here too."

(Note that the final string literal newline is not needed since print
will add one of it's own.)

HTH,
~Simon




More information about the Python-list mailing list