1
2
3
4
5
6
7
8
9
10
11
12 """Initialisation file for the Persistency package,
13 containing functions for exporting and loading Ganga objects"""
14
15 __author__ = "K.Harrison <Harrison@hep.phy.cam.ac.uk>"
16 __date__ = "21 October 2005"
17 __version__ = "1.0"
18
19 from Ganga.GPI import *
20 from Ganga.Utility.Runtime import getScriptPath, getSearchPath
21 import Ganga.Utility.logging
22 import os
23 import sys
24 import time
25 import types
26
27 logger = Ganga.Utility.logging.getLogger()
28
29 -def export( item = None, filename = "", mode = "w" ):
30
31 """Function to export Ganga objects to a file
32
33 Arguments:
34 item - Ganga object(s) [default None] to be exported
35 => item may be any of following:
36 a single Ganga object;
37 a list or tuple of Ganga objects;
38 a repository object (jobs or templates)
39 filename - String [default ''] giving relative or absolute path
40 to file where object definitions are to be exported
41 mode - String [default 'w'] giving mode in which file
42 specified by 'filename' is to be accessed:
43 'w' : write to new file
44 'a' : append to existing file
45
46 Ganga objects saved to a file with the 'export' command can
47 be loaded with the 'load' command
48
49 Return value: True if Ganga object(s) successfully written to file,
50 or False otherwise
51 """
52
53 returnValue = False
54
55 if not item or not filename:
56 logger.info( "Usage:" )
57 logger.info( "export( <GangaObject>, '<filename>', [ '<mode>' ] )" )
58 logger.info( "See also: 'help( export )'" )
59 return returnValue
60
61 modeDict = {
62 "w" : "write to new file",
63 "a" : "append to existing file" }
64
65 if mode not in modeDict.keys():
66 logger.info( "'mode' must be one of:" )
67 for key in modeDict.keys():
68 logger.info( " '%s' - %s" % ( key, modeDict[ key ] ) )
69 logger.info( "No object saved" )
70 return returnValue
71
72 filepath = fullpath( filename )
73 try:
74 outFile = file( filepath, mode )
75 except IOError:
76 logger.error( "Unable to open file '%s' for writing" % filename )
77 logger.error( "No object saved" )
78 return returnValue
79
80 isIterable = False
81
82 if ( type( item ) is types.ListType ):
83 isIterable = True
84 elif type( item ) is types.TupleType:
85 isIterable = True
86 else:
87 from Ganga.GPIDev.Lib.Registry.RegistrySliceProxy import RegistrySliceProxy
88 if isinstance(item, RegistrySliceProxy):
89 isIterable = True
90
91 if isIterable:
92 objectList = item
93 else:
94 objectList = [ item ]
95
96 if mode == "w":
97 lineList = [
98 "#Ganga# File created by Ganga - %s\n" % ( time.strftime( "%c" ) ),
99 "#Ganga#\n",
100 "#Ganga# Object properties may be freely edited before reloading into Ganga\n",
101 "#Ganga#\n",
102 "#Ganga# Lines beginning #Ganga# are used to divide object definitions,\n",
103 "#Ganga# and must not be deleted\n",
104 "\n" ]
105 outFile.writelines( lineList )
106
107 nObject = 0
108 for object in objectList:
109 try:
110 name = object._impl._name
111 category = object._impl._category
112 outFile.write( "#Ganga# %s object (category: %s)\n" \
113 % ( name, category ) )
114 object._impl.printTree( outFile, "copyable" )
115 nObject = nObject + 1
116 except AttributeError:
117 logger.info( "Unable to save item - not a GangaObject" )
118 logger.debug( "Problem item: %s" % ( repr( object ) ) )
119
120 if nObject:
121 returnValue = True
122 else:
123 logger.warning( "No objects saved to file '%s'" % filename )
124
125 outFile.close()
126
127 return returnValue
128
130 """Function to determine the full path corresponding to a given filename,
131 expanding environment variables and tilda as necessary
132
133 Argument:
134 filename - String [default ''] giving the name of a file
135
136 Return value: String giving absolute path to file
137 """
138 filepath = os.path.abspath\
139 ( os.path.expandvars( os.path.expanduser( filename ) ) )
140 return filepath
141
142 -def load( filename = "", returnList = True ):
143 """Function to load previously exported Ganga objects
144
145 Arguments:
146 filename - String [default ''] giving path to a file containing
147 definitions of Ganga objects, such as produced with
148 the 'export' function
149 => The path can be absolute, relative, or relative
150 to a directory in the search path LOAD_SCRIPTS,
151 defined in [Configuration] section of
152 Ganga configuration
153 returnList - Switch [default True] defining the return type:
154 => True : List of loaded objects is returned
155 => False : None returned - job and template objects
156 stored in job repository
157
158 Return value: List of Ganga objects or None, as determined by value
159 of argument returnList
160 """
161
162 if returnList:
163 returnValue = []
164 else:
165 returnValue = None
166
167 if not filename:
168 logger.info( "Usage:" )
169 logger.info( "load( '<filename>', [ <returnList> ] )" )
170 logger.info( "See also: 'help( load )'" )
171 return returnValue
172
173
174 searchPath = getSearchPath( "LOAD_PATH" )
175 filepath = getScriptPath( filename, searchPath )
176 try:
177 inFile = open( filepath )
178 except IOError:
179 logger.error( "Unable to open file %s" % ( str( filename ) ) )
180 logger.error( "No objects loaded" )
181 return returnValue
182
183 lineList = inFile.readlines()
184 for i in range( len (lineList) ):
185 line = lineList[ i ].strip()
186 if ( 0 == line.find( "#Ganga#" ) ):
187 lineList[ i ] = "#Ganga#"
188 itemList = ("".join( lineList ) ).split( "#Ganga#" )
189
190 objectList = []
191 for item in itemList:
192 item = item.strip()
193 if item:
194 try:
195 object = eval( item )
196 objectList.append( object )
197 except NameError:
198 logger.warning( "Unable to load object with definition %s" % item )
199 logger.warning( "Required plug-ins may not be available" )
200
201 if not objectList:
202 logger.warning( "Unable to load any objects from file %s" % filename )
203
204 if returnList:
205 returnValue = objectList
206
207 return returnValue
208