What is the best way to print the usage string ?

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Aug 4 02:16:48 EDT 2006


"Leonel Gayard" <leonel.gayard at gmail.com> writes:

> 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.

Many people have pointed you to the 'textwrap' standard library
module, which is the right general solution to be able to wrap and
dedent text.

For this particular use case, you may also want to investigate the
standard library 'optparse' module, which provides a way of defining
options as objects that contain everything the parser needs to know,
including a help message for each option which it then uses to
automatically construct a program usage message.

    <URL:http://docs.python.org/lib/module-optparse>

-- 
 \     "I cannot conceive that anybody will require multiplications at |
  `\    the rate of 40,000 or even 4,000 per hour ..."  -- F. H. Wales |
_o__)                                                           (1936) |
Ben Finney




More information about the Python-list mailing list