Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Argparse: Use an empty flag

I'm trying to write a python script using argparse which sets a value to True if -d has been set.

Here is what I'm trying:

parser.add_argument("-d", "--dynamic", required=False)

dynamic = False
if args.dynamic is not None:
  dynamic = True

I get the following error:

usage: psd.py [-h] -f FILE [-d DYNAMIC] psd.py: error: argument -d/--dynamic: expected one argument

How do I set the flag to expect 0 arguments?

like image 587
Philip Kirkbride Avatar asked Jun 30 '26 21:06

Philip Kirkbride


1 Answers

Use the action:

parser.add_argument("-d", "--dynamic", action='store_true')

You may drop the "required" kwarg.

like image 181
wim Avatar answered Jul 02 '26 09:07

wim



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!