Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: Display parse_known_args mode in usage string

When using Python's argparse module you can use parse_known_args() to parse only arguments that are known to the parser and any additional arguments are returned separately.

However, this fact is not denoted in the usage/help string. Of course I could put it in the description field of the parser, but I wonder if there's a nice way to include it in the usage line.

What I'm looking for is an output of e.g. usage: test [-h] ... instead of usage: test [-h]

like image 542
ThiefMaster Avatar asked Jul 26 '12 22:07

ThiefMaster


2 Answers

I think you could do this with a combination of format_usage() and the ArgumentParser attribute usage. Note that that section shows usage as a keyword argument to the constructor, however, inspecting the source for usage shows that you can access it after construction as parser.usage.

I imagine your final solution would look something like:

parser = argparse.ArgumentParser()
# Add arguments...
usage = parser.format_usage()
parser.usage = usage.rstrip() + ' ...\n'
like image 85
Sam Mussmann Avatar answered Sep 21 '22 06:09

Sam Mussmann


parse_known_args() is for the convenience of the programmer writing the program, not something that the user of the program needs to worry about. If you properly define your command-line arguments, argparse gives you something similar automatically:

>>> import argparse
>>> p = argparse.ArgumentParser(prog='command')
>>> x=p.add_argument("foo", nargs=argparse.REMAINDER)
>>> p.parse_args(["--help"])
usage: command [-h] ...

positional arguments:
  foo

optional arguments:
  -h, --help  show this help message and exit
like image 32
chepner Avatar answered Sep 18 '22 06:09

chepner