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 myprog.py 

or

python myprog.py -w

I tried

parser.add_argument('-w')

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 http://docs.python.org/library/argparse.html rather opaque on this question.


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 http://docs.python.org/dev/library/argparse.html#action (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.


Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

while adding the argument to parser, action = "store_true" flag sets the default value for the argument to True. So, parser.add_argument('-w', action = "store_true") should solve the error.

链接地址: http://www.djcxy.com/p/28552.html

上一篇: Python argparse:nargs ='?' 和可选参数

下一篇: Python无需参数即可指定命令行标志