[New-bugs-announce] [issue42297] [argparse] Bad error message formatting when using custom usage text

Jake Hunsaker report at bugs.python.org
Mon Nov 9 12:25:59 EST 2020


New submission from Jake Hunsaker <jhunsake at redhat.com>:

In the sos project, we build a custom `usage` string for our argparser parser, and have noticed that doing so causes error messages from argparse to be badly formatted.

For example if a bad option value is given, the error message is mangled into the last line of our usage string:

```
# python3 bin/sos report --all-logs=on
usage: sos report [options]
sos <component> [options]

[..snip...]
	collect, collector            Collect an sos report from multiple nodes simultaneously report: error: argument --all-logs: ignored explicit argument 'on'
```


This is especially strange since we build the usage string with a trailing newline character:

```
        for com in self._components:
            aliases = self._components[com][1]
            aliases.insert(0, com)
            _com = ', '.join(aliases)
            desc = self._components[com][0].desc
            _com_string += (
                "\t{com:<30}{desc}\n".format(com=_com, desc=desc)
            )
        usage_string = ("%(prog)s <component> [options]\n\n"
                        "Available components:\n")
        usage_string = usage_string + _com_string
        epilog = ("See `sos <component> --help` for more information")
        self.parser = ArgumentParser(usage=usage_string, epilog=epilog)
```


So it appears the trailing newlines are being stripped (in our case, unintentionally?). As expected, removing the trailing newline when passing `usage_string` to our parse does not change this behavior.

However, if we don't set the usage string at all when instantiating our parser, the error message is properly formatted beginning on a new line. Slightly interesting is that without the usage_string being passed, the error message is prefixed with "sos: report:" as expected for %(prog)s expansion, but when the error message is mangled `%(prog)s` is left out as well.

A little more context is available here: https://github.com/sosreport/sos/issues/2285

----------
components: Library (Lib)
messages: 380598
nosy: TurboTurtle
priority: normal
severity: normal
status: open
title: [argparse] Bad error message formatting when using custom usage text
type: behavior
versions: Python 3.6, Python 3.7, Python 3.8

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


More information about the New-bugs-announce mailing list