我有一个简单的 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