According to PEP 257 the docstring of command line script should be its usage message.
The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
So my docstring would look something like this:
<tool name> <copyright info> Usage: <prog name> [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit ...
Now I want to use the optparse module. optparse generates the "Options" sections and a "usage" explaining the command line syntax:
from optparse import OptionParser
if __name__ == "__main__":
parser = OptionParser()
(options, args) = parser.parse_args()
So calling the script with the "-h" flag prints:
Usage: script.py [options] Options: -h, --help show this help message and exit
This can be modified as follows:
parser = OptionParser(usage="Usage: %prog [options] [args]",
description="some text explaining the usage...")
which results in
Usage: script.py [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit
But how can I use the docstring here? Passing the docstring as the usage message has two problems.
- optparse appends "Usage: " to the docstring if it does not start with "Usage: "
- The placeholder '%prog' must be used in the docstring
Result
According to the answers it seems that there is no way to reuse the docstring intended by the optparse module. So the remaining option is to parse the docstring manually and construct the OptionParser. (So I'll accept S.Loot's answer)
The "Usage: " part is introduced by the IndentedHelpFormatter which can be replaced with the formatter parameter in OptionParser.__init__().