Python argparse: display parse_known_args mode in usage string

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

However, this fact is not indicated in the line use / help. Of course, I could put it in the description field of the analyzer, but I'm wondering if there is a good way to include it in the usage string.

What I'm looking for is a way out, for example. usage: test [-h] ... instead of usage: test [-h]

+6
source share
2 answers

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

I assume your final solution will look something like this:

 parser = argparse.ArgumentParser() # Add arguments... usage = parser.format_usage() parser.usage = usage.rstrip() + ' ...\n' 
+3
source

parse_known_args() intended for the convenience of the programmer writing the program, and not what the user of the program should worry about. If you correctly 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 
+2
source

Source: https://habr.com/ru/post/921435/


All Articles