问题
I'm writing a program that uses a positional argument that takes in "the rest" of the arguments, like this
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'filenames',
nargs='*',
metavar="filename(s)",
)
args = parser.parse_args()
Here I have used the metavar
parameter to get a nicer help text. But the issue is the usage
string:
>python test_argparse_plural.py -h
usage: test_argparse_plural.py [-h] [filenames) [filename(s ...]]
positional arguments:
filename(s)
optional arguments:
-h, --help show this help message and exit
It seems like it doesn't handle the (s)
part very well. I would instead like the usage
string to be either
test_argparse_plural.py [-h] [filename(s)]
or perhaps
test_argparse_plural.py [-h] [filename1, filename2, ...]
(or anything else sensible, really)
Is there any simple way to achieve this?
回答1:
I ran into the same issue. This is what I came up with:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'filenames',
nargs='+',
metavar='filename',
help='file(s) to process'
)
args = parser.parse_args()
This will produce the following usage:
nargs_plus_demo.py -h
usage: nargs_plus_demo.py [-h] filename [filename ...]
positional arguments:
filename file(s) to process
optional arguments:
-h, --help show this help message and exit
来源:https://stackoverflow.com/questions/58797637/issue-with-automatic-usage-string-from-argparse-with-nargs-and-metavar-with