Argparse: How to disallow some options in the presence of others - Python

倾然丶 夕夏残阳落幕 提交于 2021-01-27 17:54:39

问题


I have the following utility:

import argparse

parser = argparse.ArgumentParser(description='Do some action.')
parser.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
parser.add_argument('--bar', '--br', type=int, default=-1, help='do something bar')
parser.add_argument('--baz', '--bz', type=int, default=-1, help='do something baz')
parser.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')

However, if the --foo option is used, the --bat option should be disallowed, and conversely, the --bat option should only be used if --bar and --baz are present. How can I accomplish that using argparse? Sure, I could add a bunch of if / else blocks to check for that, but there's something built-in argparse that could do that for me?


回答1:


You can create mutually-exclusive groups of options with parser.add_mutually_exclusive_group:

group = parser.add_mutually_exclusive_group()
group.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
group.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')

, but for more complex dependency graphs (for example, --bat requiring --bar and --baz), argparse doesn't offer any specific support. That'd be going too far in the direction of the inner-platform effect, trying to rebuild too much of the full generality of a complete programming language within the argparse subsystem.



来源:https://stackoverflow.com/questions/39459015/argparse-how-to-disallow-some-options-in-the-presence-of-others-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!