我正在尝试在python中编写一个程序,它可以像R的保存一样工作。保存工作空间的图像。 Follwoing是我的代码,但它运行不顺畅,请帮助我使其工作
我使用了以下样本数据和绘图,以便可以对其进行测试
import shelve
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
import pandas as pd
x = np.arange(-3, 3, 0.01)
y = np.sin(np.pi*x)
fig = plt.figure()
ax = fig.add_subplot(111)
line=ax.plot(x, y)
#shelving or pickling my session
my_shelf = shelve.open('shelve.out','c') # 'n' for new
for name in dir():
if not name.startswith (('__','_','In','Out','exit','quit','get_ipython')):
try:
my_shelf[name] = globals()[name] # I didn't undersatnd why to use globals()
except Exception:
pass
print('ERROR shelving: {0}'.format(name))
my_shelf.close()
my_shelf = shelve.open('shelve.out','r')
for key in my_shelf:
globals()[key]=my_shelf[key]
my_shelf.close()
with open('save.p', 'wb') as f:
for name in dir():
if not name.startswith (('__','_','In','Out','exit','quit','get_ipython')):
try:
pickle.dump(name, f)
except Exception:
print('ERROR shelving: {0}'.format(name))
pass
with open('save.p',"rb") as f: # Python 3: open(..., 'rb')
pickle.load(f)
我将非常感谢任何帮助,对于任何错误的缩进道歉,同时粘贴溢出他们得到了改变
答案 0 :(得分:0)
莳萝模块提供了此功能。
dump_session(filename ='/ tmp / session.pkl',main = None,byref = False,** kwds)
load_session(filename ='/ tmp / session.pkl',main = None,** kwds)