来自argparse的nargs ='*'和带有可选复数“(s)"的metavar的自动用法字符串的问题 [英] Issue with automatic usage string from argparse with nargs='*' and metavar with optional plural "(s)"

查看:121
本文介绍了来自argparse的nargs ='*'和带有可选复数“(s)"的metavar的自动用法字符串的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用位置参数的程序,该位置参数接受参数的其余",像这样

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()

在这里,我使用了 metavar 参数来获得更好的帮助文本.但是问题出在 usage 字符串:

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

似乎不能很好地处理(s)部分.相反,我希望 usage 字符串为

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

或者也许

test_argparse_plural.py [-h] [filename1, filename2, ...]

(或者其他任何明智的选择,真的)

(or anything else sensible, really)

有没有简单的方法可以做到这一点?

Is there any simple way to achieve this?

推荐答案

我遇到了同样的问题.这是我想出的:

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()

这将产生以下用法:

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

这篇关于来自argparse的nargs ='*'和带有可选复数“(s)"的metavar的自动用法字符串的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆