Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ArgParse:检查参数值是否存在,否则使用默认值_Python_Argparse - Fatal编程技术网

Python ArgParse:检查参数值是否存在,否则使用默认值

Python ArgParse:检查参数值是否存在,否则使用默认值,python,argparse,Python,Argparse,我想在命令行中传递参数时存储TRUE/FALSE。但是,如果参数名称或参数未指定后不存在任何内容,则应将其存储为TRUE。 下面的代码在很大程度上实现了这一点,只是在指定了stoploging(如第二个所需输出)时,它不存储任何内容 实际产量: >>>python test.py >>>Namespace(stoplogging='True') >>>python test.py --stoplogging >>>Nam

我想在命令行中传递参数时存储TRUE/FALSE。但是,如果参数名称或参数未指定后不存在任何内容,则应将其存储为TRUE。 下面的代码在很大程度上实现了这一点,只是在指定了stoploging(如第二个所需输出)时,它不存储任何内容

实际产量:

>>>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)
  • nargs='?'
    表示0或-1参数
  • const=“True”
    当有0个参数时,将默认值设置为True

您的代码有什么输出?将其编辑到问题中。您可能正在查找
action=“store\u true”
-这意味着,如果指定了该选项,请指定值
true
。否则,当我使用
action=“store_true”
时,它被设置为
False
,我得到以下结果:用法:test.py[-h][--stoplogging]test.py:错误:参数--stoplogging:忽略显式参数'False'