【问题标题】:How to make a short and long version of a required argument using Python Argparse?如何使用 Python Argparse 制作所需参数的短版本和长版本?
【发布时间】:2015-04-22 17:05:54
【问题描述】:

我想指定一个名为inputdir 的必需参数,但我也想有一个名为i 的简写版本。我没有看到一个简洁的解决方案来做到这一点,而无需同时制作两个可选参数,然后进行自己的检查。是否有我没有看到的首选做法,或者唯一的方法是使两者都是可选的并自己进行错误处理?

这是我的代码:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inputdir", help="Specify the input directory")
parser.parse_args()

【问题讨论】:

    标签: python command-line-arguments argparse


    【解决方案1】:

    对于 flags(以 --- 开头的选项)传入选项 with 标志。您可以指定多个选项:

    parser.add_argument('-i', '--inputdir', help="Specify the input directory")
    

    name or flags option documentation

    add_argument() 方法必须知道是否需要可选参数(如 -f--foo)或位置参数(如文件名列表)。因此,传递给add_argument() 的第一个参数必须是一系列标志,或者是一个简单的参数名称。

    演示:

    >>> import argparse
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('-i', '--inputdir', help="Specify the input directory")
    _StoreAction(option_strings=['-i', '--inputdir'], dest='inputdir', nargs=None, const=None, default=None, type=None, choices=None, help='Specify the input directory', metavar=None)
    >>> parser.print_help()
    usage: [-h] [-i INPUTDIR]
    
    optional arguments:
      -h, --help            show this help message and exit
      -i INPUTDIR, --inputdir INPUTDIR
                            Specify the input directory
    >>> parser.parse_args(['-i', '/some/dir'])
    Namespace(inputdir='/some/dir')
    >>> parser.parse_args(['--inputdir', '/some/dir'])
    Namespace(inputdir='/some/dir')
    

    然而,required 参数的第一个元素只是一个占位符。 --- 选项总是 可选(这是命令行约定),从不使用此类开关指定必需的参数。相反,命令行帮助将根据传递给 add_argument() 的第一个参数显示所需参数的放置位置,占位符将不带破折号传入。

    如果您必须打破该约定并使用以--- 开头的参数无论如何,您必须自己进行检查:

    args = parser.parse_args()
    if not args.inputdir:
        parser.error('Please specify an inputdir with the -i or --inputdir option')
    

    这里parser.error() method会打印帮助信息和你的错误信息,然后退出。

    【讨论】:

    • 非常感谢您的澄清!非常感谢您的帮助。
    • 我不喜欢的是,当它打印出用法时,它不会打印出-i--inputdir。我希望用法类似于usage: [-h] [-i|--inputdir INPUTDIR];达到这种效果的东西。可能的一种方法是使用add_mutually_exclusive_group(),但这对我来说似乎有点笨拙。我想知道是否有更好的方法。
    • @searchengine27:恐怕你必须自定义help formatter class
    【解决方案2】:

    https://docs.python.org/3/library/argparse.html#required

    required=True 应该支持使参数成为必需

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2013-03-02
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2021-08-13
    • 2019-09-19
    相关资源
    最近更新 更多