如何将argparse的可选参数的默认值设置为null或为空?

时间:2016-07-22 18:37:05

标签: python argparse

我使用python argparse读取一个可选参数,该参数定义用户有时通过命令行提供的“示例文件”。我希望变量的默认值为空,即找不到文件。

parser.add_argument("--exemplar_file", help = "file to inspire book", default = '')

这样做吗?

3 个答案:

答案 0 :(得分:4)

不要设置默认值:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--exemplar_file', help='file to inspire book')

args = parser.parse_args()

print(args.exemplar_file)

# Output:
# None

答案 1 :(得分:3)

默认defaultNone(默认store操作)。一个好消息是,您的用户无法提供该值(没有字符串可转换为None)。它很容易测试

 if args.examplar_file is None:
     # do your thing
     # args.exampler_file = 'the real default'
 else:
     # use args.examplar_file

default=''没问题。试试吧。

答案 2 :(得分:0)

我认为您正在寻找这个:

 Actions action = new Actions(driver);
 action.clickAndHold(element).build().perform();

'action'可使args.fix用作None。 有关更多信息:similar problems

相关问题