检查是否设置了 argparse 可选参数 [英] Check if argparse optional argument is set or not
问题描述
我想检查用户是否设置了可选的 argparse 参数.
I would like to check whether an optional argparse argument has been set by the user or not.
我可以使用isset安全检查吗?
Can I safely check using isset?
像这样:
if(isset(args.myArg)):
#do something
else:
#do something else
这对 float/int/string 类型参数是否也一样?
Does this work the same for float / int / string type arguments?
我可以设置一个默认参数并检查它(例如,设置 myArg = -1,或为字符串设置",或NOT_SET").但是,我最终要使用的值仅在脚本的后面计算.因此,我会将其设置为 -1 作为默认值,然后稍后将其更新为其他内容.与简单地检查值是否由用户设置相比,这似乎有点笨拙.
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.
推荐答案
我认为可选参数(用 --
指定)被初始化为 None
如果它们不是提供.所以你可以用 is not None
来测试.试试下面的例子:
I think that optional arguments (specified with --
) are initialized to None
if they are not supplied. So you can test with is not None
. Try the example below:
import argparse
def main():
parser = argparse.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
这篇关于检查是否设置了 argparse 可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!