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]
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'
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
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