如何创建可选的参数? [英] How to create an argument that is optional?

查看:23
本文介绍了如何创建可选的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是用户必须使用 script.py --file c:/stuff/file.txt 有没有办法让用户选择性地使用 --file?因此,它看起来像 script.py c:/stuff/file.txt,但解析器仍然知道用户指的是 --file 参数(因为它是隐含的).>

Instead of the user having to use script.py --file c:/stuff/file.txt is there a way to let the user optionally use the --file? So instead, it would look like script.py c:/stuff/file.txt but the parser would still know that the user is referring to the --file argument (because it's implied).

推荐答案

试试这个

import argparse

class DoNotReplaceAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if not getattr(namespace, self.dest):
            setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser(description="This is an example.")
parser.add_argument('file', nargs='?', default='', help='specifies a file.', action=DoNotReplaceAction)
parser.add_argument('--file', help='specifies a file.')

args = parser.parse_args()
# check for file argument
if not args.file:
    raise Exception('Missing "file" argument')

查看帮助信息.所有参数都是可选的

Look at help message. All arguments are optional

usage: test.py [-h] [--file FILE] [file]

This is an example.

positional arguments:
  file         specifies a file.

optional arguments:
  -h, --help   show this help message and exit
  --file FILE  specifies a file.

需要注意的一点是位置 file 将覆盖可选的 --file 并将 args.file 设置为默认的 ''.为了克服这个问题,我为位置 file 使用了自定义 action.它禁止覆盖已经设置的属性.

One thing to notice is that positional file will override optional --file and set args.file to default ''. To overcome this I used custom action for positional file. It forbids overriding already set properties.

要注意的另一件事是,您可以指定默认值,而不是引发 Exception.

The other thing to notice is rather than raising an Exception you could specify default value.

这篇关于如何创建可选的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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