How to add% d to argparse help text

I ran into this problem with python 2.6.1 argparse 0.8, I need to add %d to help describe, for example.

 import argparse parser = argparse.ArgumentParser() parser.add_argument('--range', metavar='range', type=str, help='generates a list of host from given range eg "host%d.example.com 1 224"') args = parser.parse_args() 

It gives an error

 $ ./args.py -h ... python2.6/site-packages/argparse.py", line 458, in _expand_help return action.help % params TypeError: %d format: a number is required, not dict 

What I can understand, so I tried to exit % , for example.

 parser.add_argument('--range', metavar='range', type=str, help='generates a list of host from given range eg "host%%d.example.com 1 224"') 

But I still get one more error

 $ ./args.py -h ... python2.6/site-packages/argparse.py", line 252, in format_help help = self._root_section.format_help() % dict(prog=self._prog) TypeError: %d format: a number is required, not dict 

So I'm not sure how to escape from % correctly so that I can see %d in the help output

+4
source share
2 answers

Since argparse formats the string twice, giving 2 errors, the solution is to avoid % twice:

 parser.add_argument('--range', metavar='range', type=str, help='generates a list of host from given range eg "host%%%%d.example.com 1 224"') 

This is 4 % s.

+1
source

A small alternative if 4 % offends the eye.

  parser.add_argument('--range', metavar='range', type=str, help=r'generates a list of host from given range eg "host%s.example.com 1 224"' % "%%d") 
0
source

All Articles