[issue9334] argparse does not accept options taking arguments beginning with dash (regression from optparse)

Anders Kaseorg report at bugs.python.org
Fri Jul 23 00:15:39 CEST 2010


New submission from Anders Kaseorg <andersk at mit.edu>:

Porting the a2x program to argparse from the now-deprecated optparse subtly breaks it when certain options are passed:

$ a2x --asciidoc-opts --safe gitcli.txt
$ ./a2x.argparse --asciidoc-opts --safe gitcli.txt
usage: a2x [-h] [--version] [-a ATTRIBUTE] [--asciidoc-opts ASCIIDOC_OPTS]
           [--copy] [--conf-file CONF_FILE] [-D PATH] [-d DOCTYPE]
           [--epubcheck] [-f FORMAT] [--icons] [--icons-dir PATH] [-k]
           [--lynx] [-L] [-n] [-r PATH] [-s] [--stylesheet STYLESHEET]
           [--safe] [--dblatex-opts DBLATEX_OPTS] [--fop]
           [--fop-opts FOP_OPTS] [--xsltproc-opts XSLTPROC_OPTS] [-v]
a2x: error: argument --asciidoc-opts: expected one argument

Apparently argparse uses a heuristic to try to guess whether an argument looks like an argument or an option, going so far as to check whether it looks like a negative number (!).  It should _never_ guess: the option was specified to take an argument, so the following argument should always be parsed as an argument.

Small test case:

>>> import optparse
>>> parser = optparse.OptionParser(prog='a2x')
>>> parser.add_option('--asciidoc-opts',
...     action='store', dest='asciidoc_opts', default='',
...     metavar='ASCIIDOC_OPTS', help='asciidoc options')
>>> parser.parse_args(['--asciidoc-opts', '--safe'])
(<Values at 0x7f585142ef80: {'asciidoc_opts': '--safe'}>, [])

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='a2x')
>>> parser.add_argument('--asciidoc-opts',
...     action='store', dest='asciidoc_opts', default='',
...     metavar='ASCIIDOC_OPTS', help='asciidoc options')
>>> parser.parse_args(['--asciidoc-opts', '--safe'])
usage: a2x [-h] [--asciidoc-opts ASCIIDOC_OPTS]
a2x: error: argument --asciidoc-opts: expected one argument

----------
components: Library (Lib)
messages: 111221
nosy: andersk
priority: normal
severity: normal
status: open
title: argparse does not accept options taking arguments beginning with dash (regression from optparse)
versions: Python 2.7, Python 3.2, Python 3.3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9334>
_______________________________________


More information about the Python-bugs-list mailing list