如果您希望抽象出可以接受的答案,那么可以使用:
import shelve
def save_workspace(filename, names_of_spaces_to_save, dict_of_values_to_save):
'''
filename = location to save workspace.
names_of_spaces_to_save = use dir() from parent to save all variables in previous scope.
-dir() = return the list of names in the current local scope
dict_of_values_to_save = use globals() or locals() to save all variables.
-globals() = Return a dictionary representing the current global symbol table.
This is always the dictionary of the current module (inside a function or method,
this is the module where it is defined, not the module from which it is called).
-locals() = Update and return a dictionary representing the current local symbol table.
Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
Example of globals and dir():
>>> x = 3 #note variable value and name bellow
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'x': 3, '__doc__': None, '__package__': None}
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'x']
'''
print 'save_workspace'
print 'C_hat_bests' in names_of_spaces_to_save
print dict_of_values_to_save
my_shelf = shelve.open(filename,'n') # 'n' for new
for key in names_of_spaces_to_save:
try:
my_shelf[key] = dict_of_values_to_save[key]
except TypeError:
#
# __builtins__, my_shelf, and imported modules can not be shelved.
#
#print('ERROR shelving: {0}'.format(key))
pass
my_shelf.close()
def load_workspace(filename, parent_globals):
'''
filename = location to load workspace.
parent_globals use globals() to load the workspace saved in filename to current scope.
'''
my_shelf = shelve.open(filename)
for key in my_shelf:
parent_globals[key]=my_shelf[key]
my_shelf.close()
an example script of using this:
import my_pkg as mp
x = 3
mp.save_workspace('a', dir(), globals())
获取/加载工作空间:
import my_pkg as mp
x=1
mp.load_workspace('a', globals())
print x #print 3 for me
它在我运行时有效。我会承认我不明白,dir()
而且globals()
100%知道,所以我不确定是否可能会有一些怪异的警告,但到目前为止似乎仍然有效。欢迎评论:)
经过更多研究后,如果您save_workspace
按照我的建议使用globals进行调用,并且save_workspace
该函数在函数内,则无法将其保存在本地范围内,则无法正常工作。对于那个用途locals()
。发生这种情况是因为全局变量从定义函数的模块中获取全局变量,而不是从调用函数的地方获取全局变量。