Python argparse store_true and store optional opti

2019-08-14 04:24发布

This question already has an answer here:

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.

2条回答
等我变得足够好
2楼-- · 2019-08-14 04:58

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')
查看更多
做个烂人
3楼-- · 2019-08-14 05:04

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())
查看更多
登录 后发表回答