Python 检查是否设置了 argparse 可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30487767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:30:52  来源:igfitidea点击:

Check if argparse optional argument is set or not

pythonargparse

提问by Madeleine P. Vincent

I would like to check whether an optional argparse argument has been set by the user or not.

我想检查用户是否设置了可选的 argparse 参数。

Can I safely check using isset?

我可以使用isset安全检查吗?

Something like this:

像这样的东西:

if(isset(args.myArg)):
    #do something
else:
    #do something else

Does this work the same for float / int / string type arguments?

这对于 float / int / string 类型参数是否相同?

I could set a default parameter and check it (e.g., set myArg = -1, or "" for a string, or "NOT_SET"). However, the value I ultimately want to use is only calculated later in the script. So I would be setting it to -1 as a default, and then updating it to something else later. This seems a little clumsy in comparison with simply checking if the value was set by the user.

我可以设置一个默认参数并检查它(例如,设置 myArg = -1,或为字符串设置“”,或“NOT_SET”)。但是,我最终要使用的值仅在脚本的后面计算。因此,我会将其设置为 -1 作为默认值,然后稍后将其更新为其他内容。与简单地检查值是否由用户设置相比,这似乎有点笨拙。

采纳答案by Honza Osobne

I think that optional arguments (specified with --) are initialized to Noneif they are not supplied. So you can test with is not None. Try the example below:

我认为如果没有提供可选参数(用 指定--),None它们将被初始化。所以你可以用is not None. 试试下面的例子:

import argparse as ap

def main():
    parser = ap.ArgumentParser(description="My Script")
    parser.add_argument("--myArg")
    args, leftovers = parser.parse_known_args()

    if args.myArg is not None:
        print "myArg has been set (value is %s)" % args.myArg

回答by hpaulj

As @Honza notes is Noneis a good test. It's the default default, and the user can't give you a string that duplicates it.

正如@Honza 指出的那样,这is None是一个很好的测试。这是默认的default,用户不能给你一个复制它的字符串。

You can specify another default='mydefaultvalue, and test for that. But what if the user specifies that string? Does that count as setting or not?

您可以指定 another default='mydefaultvalue,并对其进行测试。但是如果用户指定了那个字符串呢?这算不算设定?

You can also specify default=argparse.SUPPRESS. Then if the user does not use the argument, it will not appear in the argsnamespace. But testing that might be more complicated:

您还可以指定default=argparse.SUPPRESS. 那么如果用户不使用该参数,它就不会出现在args命名空间中。但是测试可能更复杂:

args.foo # raises an AttributeError
hasattr(args, 'foo')  # returns False
getattr(args, 'foo', 'other') # returns 'other'

Internally the parserkeeps a list of seen_actions, and uses it for 'required' and 'mutually_exclusive' testing. But it isn't available to you out side of parse_args.

在内部parser保留一个列表seen_actions,并将其用于“必需”和“mutually_exclusive”测试。但它在parse_args.

回答by yPhil

If your argument is positional(ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameterto do this:

如果您的参数是位置参数(即它没有“-”或“--”前缀,只有参数,通常是文件名),那么您可以使用nargs 参数来执行此操作:

parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()

if args.filename is not None:
    print('The file name is {}'.format(args.filename))
else:
    print('Oh well ; No args, no problems')

回答by C.Radford

Here is my solution to see if I am using an argparse variable

这是我的解决方案,看看我是否使用了 argparse 变量

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False) 
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something

This might give more insight to the above answer which I used and adapted to work for my program.

这可能会让我更深入地了解我使用并适应为我的程序工作的上述答案。

回答by Harry Sadler

You can check an optionally passed flag with store_trueand store_falseargument action options:

您可以检查与任选通过标志store_truestore_false参数的操作选项:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument('-flag', dest='flag_exists', action='store_true')

print argparser.parse_args([])
# Namespace(flag_exists=False)
print argparser.parse_args(['-flag'])
# Namespace(flag_exists=True)

This way, you don't have to worry about checking by conditional is not None. You simply check for Trueor False. Read more about these options in the docs here

这样,您就不必担心通过 conditional 进行检查is not None。您只需检查TrueFalse。在此处的文档中阅读有关这些选项的更多信息

回答by Erasmus Cedernaes

I think using the option default=argparse.SUPPRESSmakes most sense. Then, instead of checking if the argument is not None, one checks if the argument is inthe resulting namespace.

我认为使用该选项default=argparse.SUPPRESS最有意义。然后,不是检查参数是否为 ,而是检查not None参数是否in为结果命名空间。

Example:

例子:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--foo", default=argparse.SUPPRESS)
ns = parser.parse_args()

print("Parsed arguments: {}".format(ns))
print("foo in namespace?: {}".format("foo" in ns))

Usage:

用法:

$ python argparse_test.py --foo 1
Parsed arguments: Namespace(foo='1')
foo in namespace?: True
未提供参数:
$ python argparse_test.py
Parsed arguments: Namespace()
foo in namespace?: False