Ramesh Raithatha
Ramesh Raithatha

Reputation: 544

How to parse options without any argument using optparse module

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

For example:

./log.py --ipv4 

Upvotes: 11

Views: 11720

Answers (2)

Murkantilism
Murkantilism

Reputation: 1208

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')

Upvotes: 9

lajarre
lajarre

Reputation: 5162

parser.add_option("--ipv4", action="store_true", dest="ipv4")

See http://docs.python.org/2/library/optparse.html#handling-boolean-flag-options

Upvotes: 15

Related Questions