Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 486
Andrew Avatar asked Oct 24 '25 18:10

Andrew


1 Answers

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)
like image 68
chepner Avatar answered Oct 26 '25 08:10

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!