Issue with automatic usage string from argparse with nargs='*' and metavar with optional plural “(s)”

雨燕双飞 提交于 2021-01-29 14:02:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!