Add angle brackets for required args in argparse
Mark Bourne
nntp.mbourne at spamgourmet.com
Mon Feb 20 15:39:22 EST 2023
scruel tao wrote:
> If we have the following code:
> ```
> parser = argparse.ArgumentParser(description="test")
> parser.add_argument('path')
> ```
>
> Run it without args, will get error message:
> ```
> usage: test.py [-h] path
> test.py: error: the following arguments are required: path
> ```
>
> However, I hope the message can be as the following:
> ```
> usage: test.py [-h] <path>
> test.py: error: the following arguments are required: path
> ```
The `metavar` argument to `add_argument` can be used to control how an
argument is represented in the usage text:
```
import argparse
parser = argparse.ArgumentParser(description='test')
parser.add_argument('path', metavar='<path>')
parser.parse_args()
```
Which results in:
```
usage: test.py [-h] <path>
test.py: error: the following arguments are required: <path>
```
> Or might can consider to provide a way to let user have there own style, like:
> ```
> usage: test.py [-h] path
> ```
It's also possible to create a custom help formatter, overriding
appropriate methods to control the formatting. For example:
```
import argparse
class CustomHelpFormatter(argparse.HelpFormatter):
def _get_default_metavar_for_positional(self, action):
default = super()._get_default_metavar_for_positional(action)
return f'<{default}>'
parser = argparse.ArgumentParser(
description='test',
formatter_class=CustomHelpFormatter)
parser.add_argument('path')
parser.parse_args()
```
Which results in:
```
usage: test.py [-h] <path>
test.py: error: the following arguments are required: path
```
That's a bit closer to what you asked for, since the required argument
shown in the error message doesn't include the angle brackets. It also
avoids needing to specify a `metavar` for every positional argument.
However, it is overriding a non-public method of the `HelpFormatter`
class, so might not work across all Python versions if the name or
signature of that method changes (even if it does work with all current
versions, it might break in future).
--
Mark.
More information about the Python-list
mailing list