According to the documentation on python's getopt
(I think) the options fields should behave as the getopt()
function. However I can't seem to enable optional parameters to my code:
#!/usr/bin/python
import sys,getopt
if __name__ == "__main__":
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "v::", ["verbose="])
except getopt.GetoptError, err:
print str(err)
sys.exit(1)
for o,a in opts:
if o in ("-v", "--verbose"):
if a:
verbose=int(a)
else:
verbose=1
print "verbosity is %d" % (verbose)
Results in:
$ ./testopt.py -v
option -v requires argument
$ ./testopt.py -v 1
verbosity is 1
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
By using default value: You can implement optional parameters by using default value. It is the simplest and easiest way to implement the optional parameter. In this way, you just simply define the optional parameters with their default value in the method definition.
The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is in general used for parsing an argument sequence such as sys. argv. In other words, this module helps scripts to parse command-line arguments in sys.
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.
getopt
doesn't support optional parameters. in case of long option you could do:
$ ./testopt.py --verbose=
which will result in empty-string value.
You could find argparse
module to be more flexible.
Unfortunately, there is no way. From the optparse docs:
Typically, a given option either takes an argument or it doesn’t. Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if "-a" takes an optional argument and "-b" is another option entirely, how do we interpret "-ab"? Because of this ambiguity, optparse does not support this feature.
EDIT: oops, that is for the optparse module not the getopt module, but the reasoning why neither module has "optional option arguments" is the same for both.
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