【发布时间】:2021-07-27 11:24:18
【问题描述】:
我想在命令行中传递参数时存储 TRUE/FALSE。但如果参数名称后没有任何内容或未指定参数,则应存储 TRUE。 下面的代码大部分都是这样做的,除了它在简单地指定 --stoplogging 时存储 NONE (如在第二个所需的输出中)
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--stoplogging', action='store', default="True", nargs='?')
args=parser.parse_args()
print(args)
实际输出:
>>>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')
【问题讨论】:
-
你的代码有什么输出?将其编辑到问题中。
-
您可能正在寻找
action="store_true"- 这意味着,如果指定了选项,则分配值True。否则设置为False -
当我使用
action="store_true"时,我得到以下信息: 用法:test.py [-h] [--stoplogging] test.py:错误:参数 --stoplogging:忽略显式参数 'False'