Validating positional arguments in optparse

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Oct 23 12:24:25 CEST 2009


Filip Gruszczyński wrote:
> optparse module is quite smart, when it comes to validating options,
> like assuring, that certain option must be an integer. However, I
> can't find any information about validating, that positional arguments
> were provided and I can't find methods, that would allow defining
> positional argument in OptionParser. Is it possible to do this, or was
> it intentionaly left this way?
>
>   
You can't, unlike argparse.

"

    * *The argparse module can handle positional and optional arguments,
      while optparse can handle only optional arguments*. (See
      add_argument()
      <http://argparse.googlecode.com/svn/tags/r101/doc/add_argument.html#add_argument>.)
    * The argparse module isn’t dogmatic about what your command line
      interface should look like - options like -file or /file are
      supported, as are required options. Optparse refuses to support
      these features, preferring purity over practicality.
    * The argparse module produces more informative usage messages,
      including command-line usage determined from your arguments, and
      help messages for both positional and optional arguments. The
      optparse module requires you to write your own usage string, and
      has no way to display help for positional arguments.
    * The argparse module supports action that consume a variable number
      of command-line args, while optparse requires that the exact
      number of arguments (e.g. 1, 2, or 3) be known in advance. (See
      add_argument()
      <http://argparse.googlecode.com/svn/tags/r101/doc/add_argument.html#add_argument>.)
    * The argparse module supports parsers that dispatch to
      sub-commands, while optparse requires setting
      allow_interspersed_args and doing the parser dispatch manually.
      (See add_subparsers()
      <http://argparse.googlecode.com/svn/tags/r101/doc/other-methods.html#add_subparsers>.)
    * The argparse module allows the type and action parameters to
      add_argument()
      <http://argparse.googlecode.com/svn/tags/r101/doc/add_argument.html#add_argument>
      to be specified with simple callables, while optparse requires
      hacking class attributes like STORE_ACTIONS or CHECK_METHODS to
      get proper argument checking. (See add_argument()
      <http://argparse.googlecode.com/svn/tags/r101/doc/add_argument.html#add_argument>).
    * "

That being said, I still stick with optparse. I prefer the dogmatic 
interface that makes all my exe use the exact same (POSIX) convention. I 
really don't care about writing /file instead of --file

JM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091023/d78fa019/attachment.html>


More information about the Python-list mailing list