11

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

For example:

./log.py --ipv4 

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Why does this only have one up vote (mine!... and yours too @Murkantilism ) ?
9

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.