Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
interstar Avatar asked Nov 24 '11 14:11

interstar


People also ask

How do you make an argument optional in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() .

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.


2 Answers

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 here (specifically store_true and store_false)

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

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

like image 83
Jdog Avatar answered Sep 28 '22 04:09

Jdog


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 
like image 25
user1767754 Avatar answered Sep 28 '22 04:09

user1767754