Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse options without any argument using optparse module

Tags:

python

How can I pass options without any argument and without passing any default argument?

For example:

./log.py --ipv4 
like image 985
Ramesh Raithatha Avatar asked Mar 13 '13 16:03

Ramesh Raithatha


People also ask

Which module is not used for parsing command line arguments automatically?

Getopt is not used for parsing command-line arguments automatically.

Which module is used for parsing command line arguments automatically in Python?

Python argparse module is the preferred way to parse command line arguments. It provides a lot of option such as positional arguments, default value for arguments, help message, specifying data type of argument etc.

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do I make Argparse argument optional in Python?

Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .


1 Answers

While lajarre's answer is correct, it's important to note outparse is considered deprecated.

I suggest using the newer argparse module instead.

So your code would look like:

import argparse
parser = argparse.ArgumentParser(description='This is my description')
parser.add_argument('--ipv4', action='store_true', dest='ipv4')

Using -foo or --foo flags makes the arguement optional. See this documentation for more about optional arguments.

Edit: And here's the specific documentation for the add_argument method.

Edit 2: Additionally, if you wanted to accept either -foo or --foo you could do

parser.add_argument('-ipv4', '--ipv4', action='store_true', dest='ipv4')
like image 177
Murkantilism Avatar answered Oct 23 '22 12:10

Murkantilism