6.20.5.3 Other reasons to extend optparse

Adding new types and new actions are the big, obvious reasons why you might want to extend optparse. I can think of at least two other areas to play with.

First, the simple one: OptionParser tries to be helpful by calling sys.exit() when appropriate, i.e. when there's an error on the command-line or when the user requests help. In the former case, the traditional course of letting the script crash with a traceback is unacceptable; it will make users think there's a bug in your script when they make a command-line error. In the latter case, there's generally not much point in carrying on after printing a help message.

If this behaviour bothers you, it shouldn't be too hard to ``fix'' it. You'll have to

  1. subclass OptionParser and override the error() method
  2. subclass Option and override the take_action() method--you'll need to provide your own handling of the ``help'' action that doesn't call sys.exit()

The second, much more complex, possibility is to override the command-line syntax implemented by optparse. In this case, you'd leave the whole machinery of option actions and types alone, but rewrite the code that processes sys.argv. You'll need to subclass OptionParser in any case; depending on how radical a rewrite you want, you'll probably need to override one or all of parse_args(), _process_long_opt(), and _process_short_opts().

Both of these are left as an exercise for the reader. I have not tried to implement either myself, since I'm quite happy with optparse's default behaviour (naturally).

Happy hacking, and don't forget: Use the Source, Luke.

See About this document... for information on suggesting changes.