我正在测试酸洗和酸奶getOpts,每个人都成功,但现在我正试图将两者结合起来,我遇到了麻烦。以下是我正在做的事情的片段,
#! /usr/bin/env python
from itertools import groupby, chain
import pickle
import getopt
import sys
def main():
# default values
var1 = 6
var2 = 7
var3 = 4
try:
opts, args = getopt.getopt(sys.argv[1:], 'l:z', ['load=', 'help'])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-z', '--help'):
usage()
sys.exit(2)
elif opt in ('-l', '--load'):
pkl_file = open('data.pkl', 'rb')
settings = pickle.load(pkl_file)
var1 = settings[0]
var2 = settings[1]
var3 = settings[2]
pkl_file.close()
else:
usage()
sys.exit(2)
print ("\nthe values are as follows")
print ("cvar1: " + str(var1))
print ("var2: " + str(var2))
print ("var3: " + str(var3))
if __name__ == "__main__":
main()
当腌制数据时,我使用以下代码
#! /usr/bin/env python
import pickle
settings = [3, 15, 4]
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(settings, output)
output.close()
但是,当我尝试使用'-l'标志运行时,我收到以下错误
NameError: global name 'usage' is not defined
知道为什么会这样吗?提前谢谢!
答案 0 :(得分:3)
您正在调用尚未定义的函数(usage()
)。您需要实现此功能,否则您的代码将无法运行。