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

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

问题描述

代替用户必须使用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天全站免登陆