[19895] | 1 | import shelve
|
---|
| 2 | import os.path
|
---|
| 3 |
|
---|
| 4 | def savevars(*args):
|
---|
| 5 | """
|
---|
| 6 | SAVEVARS - function to save variables to a file.
|
---|
| 7 |
|
---|
| 8 | This function saves one or more variables to a file. The names of the variables
|
---|
| 9 | must be supplied. If more than one variable is specified, it may be done with
|
---|
| 10 | lists of names and values or a dictionary of name:value pairs. All the variables
|
---|
| 11 | in the workspace may be saved by specifying the globals() dictionary, but this
|
---|
| 12 | may include a lot of extraneous data.
|
---|
| 13 |
|
---|
| 14 | Usage:
|
---|
| 15 | savevars('shelve.dat','a',a)
|
---|
| 16 | savevars('shelve.dat',['a','b'],[a,b])
|
---|
| 17 | savevars('shelve.dat',{'a':a,'b':b})
|
---|
| 18 | savevars('shelve.dat',globals())
|
---|
| 19 |
|
---|
| 20 | """
|
---|
| 21 |
|
---|
| 22 | filename=''
|
---|
| 23 | nvdict={}
|
---|
| 24 |
|
---|
| 25 | if len(args) >= 1 and isinstance(args[0],str):
|
---|
| 26 | filename=args[0]
|
---|
| 27 | if not filename:
|
---|
| 28 | filename='/tmp/shelve.dat'
|
---|
| 29 |
|
---|
| 30 | else:
|
---|
| 31 | raise TypeError("Missing file name.")
|
---|
| 32 |
|
---|
| 33 | if len(args) >= 3 and isinstance(args[1],str): # (filename,name,value)
|
---|
| 34 | for i in range(1,len(args),2):
|
---|
| 35 | nvdict[args[i]]=args[i+1]
|
---|
| 36 |
|
---|
| 37 | elif len(args) == 3 and isinstance(args[1],list) and isinstance(args[2],list): # (filename,[names],[values])
|
---|
| 38 | for name,value in zip(args[1],args[2]):
|
---|
| 39 | nvdict[name]=value
|
---|
| 40 |
|
---|
| 41 | elif len(args) == 2 and isinstance(args[1],dict): # (filename,{names:values})
|
---|
| 42 | nvdict=args[1]
|
---|
| 43 |
|
---|
| 44 | else:
|
---|
| 45 | raise TypeError("Unrecognized input arguments.")
|
---|
| 46 |
|
---|
| 47 | if os.path.exists(filename):
|
---|
[23709] | 48 | print(("Shelving variables to existing file '%s'." % filename))
|
---|
[19895] | 49 | else:
|
---|
[23709] | 50 | print(("Shelving variables to new file '%s'." % filename))
|
---|
[19895] | 51 |
|
---|
| 52 | my_shelf = shelve.open(filename,'c') # 'c' for create if not exist, else 'n' for new
|
---|
| 53 |
|
---|
[23709] | 54 | for name,value in list(nvdict.items()):
|
---|
[19895] | 55 | try:
|
---|
| 56 | my_shelf[name] = value
|
---|
[23709] | 57 | print(("Variable '%s' shelved." % name))
|
---|
[19895] | 58 | except TypeError:
|
---|
[23709] | 59 | print(("Variable '%s' not shelved." % name))
|
---|
[19895] | 60 |
|
---|
| 61 | my_shelf.close()
|
---|
| 62 |
|
---|