argparse: Ignore positional arguments if a flag is set?

蹲街弑〆低调 提交于 2021-02-08 12:01:34

问题


I want to provide the command with 3 arguments: <version>, <input file> and <output file> under normal usage. Except there's a specific flag --init, which will basically run the program without any input and output file specifications required.

I would therefore ideally have a command which usage is:

py program.py --init

OR

py program.py <version> <input file> <output file>

However, since positional arguments are always required (because all 3 are required in any other circumstance than --init), there seems to be no way to cleanly get this syntax and all I could think of would be to make the 3 positional arguments into an optional flag, raise an exception if the optional flag isn't there when --init is not called. And that all seems ugly.

My code so far:

def get_args():
    parser = argparse.ArgumentParser(description="Tool for FOO-ing a BAR.")
    parser.add_argument(dest="version", help="The version.")
    parser.add_argument(dest="input", help="The input file.")
    parser.add_argument(dest="output", help="The output file.")

    parser.add_argument("-i", "--init", dest="init", action="store_true", help="Foo Init.")

    return parser.parse_args()

To Clarify:
Either all 3 arguments (<version> <input> <output>) MUST be specified.
OR
The program is only ran with --init flag and 0 arguments should be specified.

The program should NOT accept with 0, 1 or 2 arguments specified (without the --init flag).


回答1:


parser.add_argument has a default parameter (docs) which can be used here for version, input and output parameters. Now you won't need third init param



来源:https://stackoverflow.com/questions/60979532/argparse-ignore-positional-arguments-if-a-flag-is-set

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