问题
I need to recognise if was given argument alone or with optional string or neither
parser.add_argument(???)
options = parser.parse_args()
so
./prog.py --arg
should store ''
into options.arg,
./prog.py --arg=lol
stores 'lol'
into options.arg and
./prog.py
left options.arg as None
now I have:
parser.add_argument("--arg", nargs="?",type=str,dest="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.
回答1:
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']))
results in
Namespace(arg=None)
Namespace(arg='')
Namespace(arg='lol')
回答2:
You can do it with a custom action:
import argparse
parser = argparse.ArgumentParser()
class ArgAction(argparse.Action):
def __call__(self,parser,namespace,values,option_string=None):
if values:
setattr(namespace,self.dest,values)
else:
setattr(namespace,self.dest,'')
parser.add_argument("--arg",nargs='?',action=ArgAction,dest="arg")
print parser.parse_args("--arg".split())
print parser.parse_args("--arg=foo".split())
来源:https://stackoverflow.com/questions/16041107/python-argparse-store-true-and-store-optional-option-in-one-argument