Python argparse store_true并将可选选项存储在一个参数中 [英] Python argparse store_true and store optional option in one argument
本文介绍了Python argparse store_true并将可选选项存储在一个参数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要识别是单独给出参数还是使用可选字符串,或者都不给出参数
I need to recognise if was given argument alone or with optional string or neither
parser.add_argument(???)
options = parser.parse_args()
如此
./prog.py --arg
应将''
存储到options.arg中,
should store ''
into options.arg,
./prog.py --arg=lol
将'lol'
存储到options.arg和
stores 'lol'
into options.arg and
./prog.py
左options.arg为None
left options.arg as None
现在我有
parser.add_argument("--arg", nargs="?",type=str,dest="arg")
,但是当我以./prog.py --arg
options.arg的身份运行我的程序时,arg仍然是None
.识别--arg的唯一方法是将其作为./prog.py --arg=
运行,这对我来说是个问题.
but when I run myprogram as ./prog.py --arg
options.arg remains None
. Only way to recognise --arg was given is run it as ./prog.py --arg=
and this is problem for me.
推荐答案
使用 const
关键字:
Use the const
keyword:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--arg", nargs="?", type=str, dest="arg", const="")
print(parser.parse_args([]))
print(parser.parse_args(['--arg']))
print(parser.parse_args(['--arg=lol']))
结果
Namespace(arg=None)
Namespace(arg='')
Namespace(arg='lol')
这篇关于Python argparse store_true并将可选选项存储在一个参数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文