Ramesh Raithatha Ramesh Raithatha - 1 year ago 129
Python Question

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

Answer Source

While lajarre's answer is correct, it's important to note optparse is considered deprecated. I suggest using the newer argparse module instead.

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 the required documentation for more about optional arguments.

Here's the specific documentation for the add_argument method.

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

parser.add_argument('-ipv4', '--ipv4', action='store_true', dest='ipv4')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download