根据python getopt
(我认为)的文档,选项字段应该表现为getopt()
函数。但是我似乎无法为我的代码启用可选参数:
#!/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)
结果是:
$ ./testopt.py -v
option -v requires argument
$ ./testopt.py -v 1
verbosity is 1