I have a default value that contains a '%' which I also insert in to the help doc of my argument. E.g.:
default = "5% foo"
animrender_group.add_argument(
"--foo",
default=default,
help="Foo amount. Default: %s" % default,
)
args = parser.parse_args()
Argparse errors on parse_args()
[snip]
args = parser.parse_args()
[snip]"../python2.5/site-packages/argparse.py", line 622, in _expand_help
return self._get_help_string(action) % params
ValueError: unsupported format character 'O' (0x4f) at index 83
I had tried a traditional escape character, which did not work. Then I found a comment about using a '%' as an escape character and this worked. E.g.:
default = "5% foo"
foo_group.add_argument(
"--foo",
default=default,
help="Foo amount. Default: %s" % default.replace(r"%", r"%%")),
)
args = parser.parse_args()
I'm glad I don't need to replace all '%' with '[percent sign]'. Hah.
Another way to include defaults is with a %(default)s
in the help line.
p=argparse.ArgumentParser()
p.add_argument('--foo', default="5% foo", help="Foo amount. Default: %(default)s")
p.print_help()
which produces
usage: ipython [-h] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
--foo FOO Foo amount. Default: 5% foo
From the argparse
documentation:
The help strings can include various format specifiers to avoid repetition of things like the program name or the argument default. The available specifiers include the program name, %(prog)s and most keyword arguments to add_argument(), e.g. %(default)s, %(type)s, etc.:
If you do not have a default value and just want to have a percentage sign in the help message, add a another %
to escape it:
import argparse
p=argparse.ArgumentParser()
p.add_argument('--foo', help="Foo is always 100%%!")
p.print_help()
Which gives you:
usage: [-h] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
--foo FOO Foo is always 100%!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With