Python Argparse Store_true And Store Optional Option In One Argument
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
Solution 1:
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())
Post a Comment for "Python Argparse Store_true And Store Optional Option In One Argument"