[New-bugs-announce] [issue41600] Expected behavior of argparse given quoted strings

Vegard Stikbakke report at bugs.python.org
Thu Aug 20 07:24:14 EDT 2020


New submission from Vegard Stikbakke <vegard.stikbakke at gmail.com>:

I'm not sure if this is a bug, but I had a problem when I was trying to use argparse recently, and I was wondering about the expected behavior.

For context: We invoke a Python program from a deployment tool, where we provide input in a text box. We were using argparse to read and parse the input arguments. The scenario we had was we were requiring two named arguments to be given, as illustrated in the minimal example below.

```
# a.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--a", required=True)
parser.add_argument("--b", required=True)
parser.parse_args()
```

When invoking this program from this deployment tool giving `--a=1 --b=2` as input, we got the error message `a.py: error: the following arguments are required: --a, --b`.

As it turns out, the input was provided in the same way as if you had given the program a quoted string in the shell:

```
$ python a.py "--a=1 --b=2"
usage: a.py [-h] --a A --b B
a.py: error: the following arguments are required: --a, --b
```

When given a quoted string like this, `sys.argv` only has two elements, namely `a.py` and `--a=1 --b=2`. This was new to me! But it makes sense.

This was a bit annoying! One way to get around it, which we did indeed implement, is to mutate `sys.argv`, effectively unpacking the input string such that `sys.argv` ends up as `["a.py", "--a=1`, `--b=2`].

Given that the string contains named arguments, it seems to me that it could be possible, and safe, to unpack this quoted string. Would that make sense? Or am I using it incorrectly? Or is there some other way to provide input such that I don't have to do this hack that I mentioned?

If we make a similar program where the arguments `a` and `b` are not named arguments, but rather positional arguments,

```
# b.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a")
parser.add_argument("b")
parser.parse_args()
```

and we call the program as before with `python b.py "1 2"`, then `a` will be set to the string `1 2`, whereas `b` will not be set (and so the program will, of course, exit). This seems entirely reasonable. And perhaps it isn't possible to both get this behaviour, as well as the behaviour that I mentioned above.

----------
components: Library (Lib)
messages: 375702
nosy: vegarsti
priority: normal
severity: normal
status: open
title: Expected behavior of argparse given quoted strings
type: enhancement
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41600>
_______________________________________


More information about the New-bugs-announce mailing list