【发布时间】:2017-02-27 05:38:42
【问题描述】:
我正在尝试用 python 编写一个程序,它几乎可以像 R 的保存一样工作。保存您的工作区的图像。以下是我的代码,但运行不顺畅,请帮助我使其工作
我使用了以下示例数据和图表,以便对其进行测试
Attempt1 - 使用 Shelve、字典类型的工作空间保存
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()
这次再尝试一次 Pickle:
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)
我将非常感谢任何帮助,对任何错误缩进表示歉意,同时粘贴他们得到更改的溢出
【问题讨论】:
标签: python pandas pickle workspace shelve