How can I pass options without any argument and without passing any default argument?
For example:
./log.py --ipv4
Getopt is not used for parsing command-line arguments automatically.
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.
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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 .
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With