Option accepted with and without value

前端 未结 2 682
长发绾君心
长发绾君心 2021-01-21 07:09

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

I

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 07:42

    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)
    

    Demo:

    >>> 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)
    

提交回复
热议问题