带有或不带价值的期权被接受
问题描述:
我有一个小脚本,我需要它能够接受带有值和没有值的参数.
I have a small script and I need it to be able to accept parameter with value and withou value.
./cha.py --pretty-xml
./cha.py --pretty-xml=5
我有这个.
parser.add_argument('--pretty-xml', nargs='?', dest='xml_space', default=4)
但是当我在xml_space中使用--pretty-xml时将为"none".如果我不写此参数,则在xml_space中存储默认值.我需要完全相反.
But when I use --pretty-xml in xml_space will be 'none'. If I dont write this parameter in xml_space is stored the default value. I would need the exact opposite.
答
不使用default
参数,而是使用自定义Action
:
Leave out the default
parameter and use a custom Action
instead:
class PrettyXMLAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if not values:
values = 4
setattr(namespace, self.dest, values)
parser.add_argument('--pretty-xml', nargs='?', type=int, dest='xml_space', action=PrettyXMLAction)
演示:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--pretty-xml', nargs='?', type=int, dest='xml_space', action=PrettyXMLAction)
PrettyXMLAction(option_strings=['--pretty-xml'], dest='xml_space', nargs='?', const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--pretty-xml'.split())
Namespace(xml_space=4)
>>> parser.parse_args('--pretty-xml=5'.split())
Namespace(xml_space=5)
>>> parser.parse_args(''.split())
Namespace(xml_space=None)