Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/misc/db.py
4045 views
1
"""
2
Saving Sage objects to a file
3
"""
4
5
#*****************************************************************************
6
# Copyright (C) 2004 William Stein <[email protected]>
7
#
8
# Distributed under the terms of the GNU General Public License (GPL)
9
#
10
# This code is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
# General Public License for more details.
14
#
15
# The full text of the GPL is available at:
16
#
17
# http://www.gnu.org/licenses/
18
#*****************************************************************************
19
20
21
import cPickle
22
import os
23
import misc
24
25
PATH = misc.SAGE_ROOT + "/db"
26
27
USE_DB = False
28
29
def path():
30
from sage.misc.misc import sage_makedirs
31
sage_makedirs(PATH)
32
33
def save(x, filename, bzip2=False, gzip=False):
34
"""
35
save(x, filename):
36
37
Saves x to a file. Pretty much the only constraint on x is that
38
it have no circular references (it must be Python pickle-able).
39
This uses the pickle module, so data you save is *guaranteed*
40
to be readable by future versions of Python.
41
42
INPUT:
43
x -- almost arbitrary object
44
filename -- a string
45
46
OUTPUT:
47
Creates a file named filename, from which the object x
48
can be reconstructed.
49
"""
50
51
o=open(filename,"w")
52
# Note: don't use protocol 2 here (use 1), since loading doesn't work
53
# on my extension types.
54
cPickle.dump(x,o,1)
55
o.close()
56
if bzip2:
57
os.system("bzip2 -f %s"%filename)
58
if gzip:
59
os.system("gzip -f %s"%filename)
60
61
62
def load(filename, bzip2=False, gzip=False):
63
"""
64
load(filename):
65
66
Loads an object from filename and returns it.
67
68
INPUT:
69
filename -- a string that defines a valid file. If the
70
file doesn't exist then an IOError exception is raised.
71
72
OUTPUT:
73
An almost arbitrary object.
74
"""
75
if bzip2:
76
os.system("bunzip2 -f -k %s"%(filename + ".bz2"))
77
if gzip:
78
os.system("cat %s.gz | gunzip -f > %s"%(filename,filename))
79
assert os.path.exists(filename)
80
o = open(filename,"r")
81
X = cPickle.load(o)
82
if bzip2 or gzip:
83
os.remove(filename)
84
return X
85
86
87
def save_db(x):
88
"""
89
Save x to the database. x must define a filename method.
90
"""
91
path()
92
fn = PATH + x.filename()
93
save(x,fn)
94
os.system("bzip2 -f %s"%fn)
95
96
97
def load_db(x):
98
"""
99
Load x from the database. x must define a filename method.
100
"""
101
fn = PATH + x.filename()
102
if os.path.exists(fn + ".bz2"):
103
print "Loading %s from %s."%(x,x.filename())
104
os.system("bunzip2 -f -k %s"%(fn + ".bz2"))
105
o=open(fn,"r")
106
x = cPickle.load(o)
107
os.remove(fn)
108
return x
109
else:
110
return None
111
112