pythonargparse

How to require arguments in argparse and make them non-positional?


I have a Python script where I would like to force all required arguments to be named (non-positional).

So the following should work:

python myscript --arg1 arg1 --arg2 arg2
python myscript --arg2 arg2 --arg1 arg1

But the following should fail:

python myscript arg1 arg2
python myscript --madeUpArg arg1 --arg2 arg2

From what I can tell, in argparse if you make something required, it becomes a positional argument, so both of the second examples that I want to fail will succeed (even the second case, with the made up argument!). How do I get desired functionality?


Solution

  • No argument you haven't defined will be accepted as long as you don't call parse_known_args explicitly.

    To make an otherwise optional argument required, use the required keyword argument when defining it.

    p = argparse.ArgumentParser()
    p.add_argument("--arg1", required=True)
    p.add_argument("--arg2", required=True)