如何使用Python Argparse生成所需参数的短版本和长版本?

2024-05-23 22:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想指定一个名为inputdir的必需参数,但我也希望有一个名为i的速记版本。我看不出一个简洁的解决方案来做到这一点,不做两个可选的参数,然后做我自己的检查。是否有一个我没有看到的首选实践,或者唯一的方法是使两者都是可选的,并做我自己的错误处理?

这是我的代码:

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

Tags: 方法代码import版本addparser参数argparse
1条回答
网友
1楼 · 发布于 2024-05-23 22:21:31

对于标志(以---开头的选项),传入带有标志的选项。可以指定多个选项:

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

请参见name or flags option documentation

The add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name.

演示:

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

这里^{} method将打印帮助信息和错误消息,然后退出。

相关问题 更多 >