Search code examples
pythonoptparse

Proper help for arguments


Python optparse works very good when script usage is something like this

%prog [options] [args]

But I need to write help for script with 1 required argument, so usage will be like this

%prog action [options] [args]

You can see something similar when you use Subversion - its usage string is

svn <subcommand> [options] [args]

So my question is: is it possible to prepare help for required argument with optparse in the manner of Subversion? As a result I want to see help like this:

Usage: python myscript.py action [options] [args]

Available actions:
  foo
  bar

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -v, --verbose         Verbose mode. Output debug log to stdout.

Solution

  • I think a good solution for you is argparse, which has been proposed for inclusion in Python 2.7 and 3.2. It handles subcommands, I believe as you want, and the linked page includes a link to a page on porting your code from optparse.

    See also the question command-line-arguments-in-python, into which someone edited a list of references that appears to include exactly the same thing you want: