Option accepted with and without value

前端 未结 2 694
长发绾君心
长发绾君心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 07:36

    Use the const keyword:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--pretty-xml", nargs="?", type=int, dest="xml_space", const=4)
    print(parser.parse_args([]))
    print(parser.parse_args(['--pretty-xml']))
    print(parser.parse_args(['--pretty-xml=5']))
    

    results in

    Namespace(xml_space=None)
    Namespace(xml_space=4)
    Namespace(xml_space=5)
    

提交回复
热议问题