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

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

问题描述

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

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)"的元变量的问题;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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