python, argparse: enable input parameter when another one has been specified

前端 未结 3 1564
悲&欢浪女
悲&欢浪女 2021-01-04 08:34

In my python script, I want to be able to use an optional input parameter only when another optional parameter has been specified. Example:

$ python         


        
3条回答
  •  执念已碎
    2021-01-04 09:20

    One idea would be to manually check the output of calling parser.parse_args() and raise an exception or otherwise fail if --parameter2 is used but --parameter1 isn't.

    You could also try setting a custom action (scroll down a bit) to --parameter2 check if --parameter1 exists inside the namespace.

    Finally, you could try using subparsers, although I don't know if it'll let you specify a value for --parameter1.

提交回复
热议问题