【发布时间】:2019-08-27 03:43:54
【问题描述】:
如何检查标志 --load 是否存在?
#!/usr/bin/env python3
import argparse
import os
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path')
args = parser.parse_args()
print(args)
使用--load 调用脚本会输出以下内容:
Namespace(load=None)
我不能省略nargs='?' 并使用action='store_true',因为我想允许传递一个参数,例如--load abcxyz。
添加action='store_true'和nargs='?'会产生以下错误:
parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path', action='store_true')
File "/usr/lib/python3.6/argparse.py", line 1334, in add_argument
action = action_class(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'nargs'
【问题讨论】:
-
带“?”您可以指定
default和const参数。试试看,或在文档中查找const(或之前的 SOargparse问题)。 -
A
store_true动作定义为nargs=0;它不需要争论。尝试重新定义它以采用不同的nargs是没有用的。