如何保存当前python会话中的所有变量? [英] How to save all the variables in the current python session?

查看:82
本文介绍了如何保存当前python会话中的所有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存当前python环境中的所有变量.似乎一种选择是使用pickle"模块.但是,我不想这样做有两个原因:

I want to save all the variables in my current python environment. It seems one option is to use the 'pickle' module. However, I don't want to do this for 2 reasons:

  1. 我必须为每个变量调用 pickle.dump()
  2. 当我想检索变量时,我必须记住我保存变量的顺序,然后执行一个pickle.load()来检索每个变量.
  1. I have to call pickle.dump() for each variable
  2. When I want to retrieve the variables, I must remember the order in which I saved the variables, and then do a pickle.load() to retrieve each variable.

我正在寻找一些可以保存整个会话的命令,这样当我加载这个保存的会话时,我的所有变量都会被恢复.这可能吗?

I am looking for some command which would save the entire session, so that when I load this saved session, all my variables are restored. Is this possible?

我想我不介意为我想保存的每个变量调用 pickle.dump(),但是记住保存变量的确切顺序似乎很重要限制.我想避免这种情况.

I guess I don't mind calling pickle.dump() for each variable that I would like to save, but remembering the exact order in which the variables were saved seems like a big restriction. I want to avoid that.

推荐答案

如果您使用 shelve,您不必记住对象被腌制的顺序,因为 shelve 为您提供了一个类似字典的对象:

If you use shelve, you do not have to remember the order in which the objects are pickled, since shelve gives you a dictionary-like object:

搁置您的工作:

import shelve

T='Hiya'
val=[1,2,3]

filename='/tmp/shelve.out'
my_shelf = shelve.open(filename,'n') # 'n' for new

for key in dir():
    try:
        my_shelf[key] = globals()[key]
    except TypeError:
        #
        # __builtins__, my_shelf, and imported modules can not be shelved.
        #
        print('ERROR shelving: {0}'.format(key))
my_shelf.close()

恢复:

my_shelf = shelve.open(filename)
for key in my_shelf:
    globals()[key]=my_shelf[key]
my_shelf.close()

print(T)
# Hiya
print(val)
# [1, 2, 3]

这篇关于如何保存当前python会话中的所有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆