问题
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