Python argparse store_true and store optional option in one argument [duplicate]

本秂侑毒 提交于 2019-12-11 04:18:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!