What is the best way to print the usage string ?

Steven Bethard steven.bethard at gmail.com
Fri Aug 4 12:09:38 EDT 2006


Ben Finney wrote:
> "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:])
>>
[snip]
> 
> 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>

FWIW, here's what the optparse code might look like:

     parser = optparse.OptionParser(
         usage='%prog arg1 [arg2...]',
         description='concatenates the arguments with a colon (:) '
                     'between them')
     options, args = parser.parse_args()
     if not args:
         parser.error('wrong number of arguments')
     print ':'.join(args)

The optparse module doesn't do anything for positional arguments, so you 
have to check them afterwards and issue an error as necessary. It also 
doesn't know how to construct your usage message, so you have to write 
this by hand. To handle these two things automatically, see my other 
post on the argparse module[1].

STeVe

[1] http://mail.python.org/pipermail/python-list/2006-August/354792.html



More information about the Python-list mailing list