GetOpt seems doesn't work when I specify a command line option, throws exception, this file named o.py:
import getopt
import sys
opts,args = getopt.getopt(sys.argv[1:], "m:p:", ['mode', 'perf'])
for opt_name,opt_value in opts:
if opt_name in ('--mode'):
print opt_name
continue
if opt_name in ('--perf'):
print opt_name
continue
Then I get runtime exception when:
python o.py --mode=a
Traceback (most recent call last):
File "o.py", line 3, in <module>
opts,args = getopt.getopt(sys.argv[1:], "m:p:", ['mode', 'perf'])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 88, in getopt
opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 159, in do_longs
raise GetoptError('option --%s must not have an argument' % opt, opt)
getopt.GetoptError: option --mode must not have an argument
opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 159, in do_longs raise GetoptError('option --%s must not have an argument' % opt, opt) getopt.GetoptError: option --mode must not have an argument
So where did I get wrong and how to fix it?
Your long option names are missing a trailing =
. See docs, namely:
longopts, if specified, must be a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('=')...
I.e.
opts,args = getopt.getopt(sys.argv[1:], "m:p:", ['mode=', 'perf='])