interstar interstar - 1 year ago 532
Python Question

Python argparse command line flags without arguments

How do I add an optional flag to my command line args?

eg. so I can write



python -w

I tried


But I just get an error message saying

Usage [-w W]
error: argument -w: expected one argument

which I take it means that it wants an argument value for the -w option. What's the way of just accepting a flag?

I'm finding rather opaque on this question.

Answer Source

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look at (specifically store_true and store_false)

parser.add_argument('-w', action='store_true')

Edit: As Sven points out, a default value in this case is superfluous.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download