I'm testing out pickling & getOpts, have been successful with each individually, but now that I'm trying to combine the two I'm having trouble. Below is a snippet of what I'm doing,
#! /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()
and when pickling the data I use the following code
#! /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()
However, when I try to run with the '-l' flag, I get the following error
NameError: global name 'usage' is not defined
Any idea why this is happening? Thanks in advance!
You are calling a function you haven't defined (usage()
). You need to implement this function, or else your code wont' run.