Title: User input to argparse raises Index_Error: "-a=" on a 'store_true' action
Type: crash Stage: needs patch
Components: Library (Lib) Versions: Python 3.8, Python 3.7, Python 2.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: paul.j3, xtreak
Priority: normal Keywords:

Created on 2019-03-12 01:36 by paul.j3, last changed 2019-03-12 02:49 by xtreak.

Messages (1)
msg337709 - (view) Author: paul j3 (paul.j3) * (Python triager) Date: 2019-03-12 01:36
Test case:

    parser = argparse.ArgumentParser()
    parser.add_argument("-a", action="store_true")
    args = parser.parse_args("-a=".split())

raises an Index_Error, which is not caught by the argparse error mechanism.

This is an unusual case, the coincidence of several user errors - 'store_true' which shouldn't take an argument and a short optional with a bare =.  So it's unlikely to occur.  Still, argparse shouldn't ever respond to a command line value with an uncaught error.

The traceback shows that it occurs during the handling of the explicit_arg in consume_optional.

Traceback (most recent call last):
  File "", line 5, in <module>
    args = parser.parse_args("-a=".split())
  File "/usr/lib/python3.6/", line 1743, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/usr/lib/python3.6/", line 1775, in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
  File "/usr/lib/python3.6/", line 1981, in _parse_known_args
    start_index = consume_optional(start_index)
  File "/usr/lib/python3.6/", line 1881, in consume_optional
    option_string = char + explicit_arg[0]
IndexError: string index out of range

The issue was raised in a Stackoverflow question, where I and the poster explore why it occurs, and possible fixes.
Date User Action Args
2019-03-12 02:49:00xtreaksetnosy: + xtreak

versions: + Python 2.7, Python 3.7, Python 3.8
2019-03-12 01:36:10paul.j3create