Python ArgParse:检查参数值是否存在,否则使用默认值
我想在命令行中传递参数时存储TRUE/FALSE。但是,如果参数名称或参数未指定后不存在任何内容,则应将其存储为TRUE。 下面的代码在很大程度上实现了这一点,只是在指定了stoploging(如第二个所需输出)时,它不存储任何内容 实际产量:Python ArgParse:检查参数值是否存在,否则使用默认值,python,argparse,Python,Argparse,我想在命令行中传递参数时存储TRUE/FALSE。但是,如果参数名称或参数未指定后不存在任何内容,则应将其存储为TRUE。 下面的代码在很大程度上实现了这一点,只是在指定了stoploging(如第二个所需输出)时,它不存储任何内容 实际产量: >>>python test.py >>>Namespace(stoplogging='True') >>>python test.py --stoplogging >>>Nam
>>>python test.py
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging
>>>Namespace(stoplogging='None')
>>>python test.py --stoplogging=True
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging=False
>>>Namespace(stoplogging='False')
期望输出:
>>>python test.py
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging=True
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging=False
>>>Namespace(stoplogging='False')
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--stoplogging', action='store', default="True", const="True", nargs="?")
args=parser.parse_args()
print(args)
我找到了一个适合我期望的输出的解决方案:
>>>python test.py
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging=True
>>>Namespace(stoplogging='True')
>>>python test.py --stoplogging=False
>>>Namespace(stoplogging='False')
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--stoplogging', action='store', default="True", const="True", nargs="?")
args=parser.parse_args()
print(args)
表示0或-1参数nargs='?'
当有0个参数时,将默认值设置为Trueconst=“True”
action=“store\u true”
-这意味着,如果指定了该选项,请指定值true
。否则,当我使用action=“store_true”
时,它被设置为False
,我得到以下结果:用法:test.py[-h][--stoplogging]test.py:错误:参数--stoplogging:忽略显式参数'False'