optparse: simulating ‘–help’
Summary
Getting optparse to show a summary of script options under program control.
What do you use optparse for ?
optparse is a Python standard library for parsing command-line options.
optparse provides a relatively simple way of
* defining a set of command line arguments which the user may enter
* parsing the command line entered and storing the results of the parse
I need help !
By default optparse will respond to a either of :
<yourscript> -h
or
<yourscript> --help
by printing a summary of your scripts options.
What I learned today
In the script I was working on today I wanted to respond to the user not entering any argument at all by printing a summary of all options available (in other words as if they user had entered ‘–help’ or ‘-h’ as an argument).
There is a way you can do this but for some reason it’s not in the list of OptionParser methods shown in the documentation.
print_help()
If you call the method ‘print_help’ as shown in the code below optparse will respond by by printing the same text that would be shown if the user were to enter an argument of ‘–help’.
parser = OptionParser(description=desc, usage=usage) parser.add_option( "-i", "--inbox", action="store", dest="inbox", metavar="INBOX", help="Location of INBOX") parser.add_option( "-o", "--outpath", action="store", dest="outpath", metavar="PATH", help="PATH to output csv file") parser.add_option( "-v", "--verbose", action="store_true", dest="verbose", help="Show each file processed") (options, args) = parser.parse_args() if (options.inbox is None) and (options.outpath is None): parser.print_help() exit(-1) elif not os.path.exists(options.inbox): parser.error('inbox location does not exist') elif not os.path.exists(os.path.dirname(options.outpath)): parser.error('path to ouput location does not exist') return options