我有一个简单的python脚本,它带有三个参数-f -l -a。我希望-a是一个可选参数,使用try / except除了最有效的方法来实现这一点(我想如果他们也没有传递所需的参数我需要捕获异常)?这是脚本,提前谢谢:
try:
(options, args) = getopt.getopt(sys.argv[1:], 'f:l:a:', ['first=', 'last=', 'age='] )
except getopt.GetoptError:
help()
for option in options:
if option[0] == '-f':
firstName = option[1]
elif option[0] == '-l':
lastName = option[1]
elif option[0] == '-a':
personAge = option[1]
if (firstName is None):
print >>sys.stderr, "Missing first name"
sys.exit(1)
if (lastName is None):
print >>sys.stderr, "Missing first name"
sys.exit(1)
try:
(personAge is None)
except NameError:
print("Setting personAge to unknown")
personAge = 'Unknown'
print firstName + " " + lastName + " " + personAge