python保存变量_如何在当前python会话中保存所有变量?

如果您希望抽象出可以接受的答案,那么可以使用:

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__': , '__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

它在我运行时有效。 我承认我不完全理解save_workspace和save_workspace,所以我不确定是否可能会有一些怪异的警告,但到目前为止似乎仍然有效。 欢迎评论:)

经过更多研究后,如果您按我建议的全局变量调用save_workspace,并且save_workspace在函数内,则如果您想在本地范围内保存Veriable,它将无法按预期工作。 为此,请使用locals()。这是因为全局变量从定义函数的模块中获取全局变量,而不是从调用函数的位置获取全局变量。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值