2

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?

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • Duplicate of http://stackoverflow.com/questions/8259001/python-argparse-command-line-flags-without-arguments – Rahul Apr 04 '17 at 17:40

1 Answers1

10

Use the action:

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

You may drop the "required" kwarg.

wim
  • 338,267
  • 99
  • 616
  • 750
  • When I do this I don't get the error but dynamic is always equal to True even when I don't set the flag. – Philip Kirkbride Apr 04 '17 at 17:41
  • 2
    @PhilipKirkbride: It sounds like you're still doing the `if args.dynamic is not None: ...` thing. If so, stop doing that. `store_true` makes the argument default to `False`, not `None`, if not provided. – user2357112 Apr 04 '17 at 17:42
  • ah nvm I see how this should be done args.dynamic will be True or False but always exist – Philip Kirkbride Apr 04 '17 at 17:43