Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse errors with '%' in help string

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
like image 842
Rafe Avatar asked Jan 16 '14 17:01

Rafe


3 Answers

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.

like image 96
Rafe Avatar answered Nov 17 '22 05:11

Rafe


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.:

like image 20
hpaulj Avatar answered Nov 17 '22 04:11

hpaulj


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%!
like image 4
jonatan Avatar answered Nov 17 '22 03:11

jonatan