PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/Wrapping/WrapITK/Languages/Python/itkBase.py

https://github.com/paniwani/ITK
Python | 242 lines | 218 code | 2 blank | 22 comment | 1 complexity | 05f4b10f8122961e43ca2bb8ed5c9d5b MD5 | raw file
  1. #==========================================================================
  2. #
  3. # Copyright Insight Software Consortium
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0.txt
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. #==========================================================================*/
  18. import os, os.path, sys, imp, inspect, itkConfig, itkTemplate
  19. def LoadModule(name, namespace = None):
  20. """This function causes a SWIG module to be loaded into memory after its dependencies
  21. are satisfied. Information about the templates defined therein is looked up from
  22. a config file, and PyTemplate instances for each are created. These template
  23. instances are placed in a module with the given name that is either looked up
  24. from sys.modules or created and placed there if it does not already exist.
  25. Optionally, a 'namespace' parameter can be provided. If it is provided, this
  26. namespace will be updated with the new template instantiations.
  27. The raw classes loaded from the named module's SWIG interface are placed in a
  28. 'swig' sub-module. If the namespace parameter is provided, this information will
  29. be placed in a sub-module named 'swig' therein as well. This latter submodule
  30. will be created if it does not already exist."""
  31. # find the module's name in sys.modules, or create a new module so named
  32. this_module = sys.modules.setdefault(name, imp.new_module(name))
  33. # if this library and it's template instantiations have already been loaded
  34. # into sys.modules, bail out after loading the defined symbols into 'namespace'
  35. if hasattr(this_module, '__templates_loaded'):
  36. if namespace is not None:
  37. swig = namespace.setdefault('swig', imp.new_module('swig'))
  38. swig.__dict__.update(this_module.swig.__dict__)
  39. # don't worry about overwriting the symbols in namespace -- any common
  40. # symbols should be of type itkTemplate, which is a singleton type. That
  41. # is, they are all identical, so replacing one with the other isn't a
  42. # problem.
  43. for k, v in this_module.__dict__.items():
  44. if not (k.startswith('_') or k == 'swig'): namespace[k] = v
  45. return
  46. # We're definitely going to load the templates. We set templates_loaded here
  47. # instead of at the end of the file to protect against cyclical dependencies
  48. # that could kill the recursive lookup below.
  49. this_module.__templates_loaded = True
  50. # For external projects :
  51. # If this_module name (variable name) is in the module_data dictionnary, then
  52. # this_module is an installed module (or a previously loaded module).
  53. # Otherwise, it may come from an external project. In this case, we must
  54. # search the Configuration/<name>Config.py file of this project.
  55. try:
  56. module_data[name]
  57. except:
  58. file = inspect.getfile(this_module)
  59. path = os.path.dirname(file)
  60. data = {}
  61. try:
  62. # for a linux tree
  63. execfile(os.path.join(path, 'Configuration', name + 'Config.py'), data)
  64. except:
  65. try:
  66. # for a windows tree
  67. execfile(os.path.join(path, '..', 'Configuration', name + 'Config.py'), data)
  68. except:
  69. data=None
  70. if(data):
  71. module_data[name] = data
  72. # Now, we we definitely need to load the template instantiations from the
  73. # named module, and possibly also load the underlying SWIG module. Before we
  74. # can load the template instantiations of this module, we need to load those
  75. # of the modules on which this one depends. Ditto for the SWIG modules.
  76. # So, we recursively satisfy the dependencies of named module and create the
  77. # template instantiations.
  78. # Dependencies are looked up from the auto-generated configuration files, via
  79. # the module_data instance defined at the bottom of this file, which knows how
  80. # to find those configuration files.
  81. data = module_data[name]
  82. if data:
  83. deps = list(data['depends'])
  84. deps.sort()
  85. for dep in deps:
  86. LoadModule(dep, namespace)
  87. if itkConfig.ImportCallback: itkConfig.ImportCallback(name, 0)
  88. # SWIG-generated modules have 'Python' appended. Only load the SWIG module if
  89. # we haven't already.
  90. swigModuleName = name + "Python"
  91. loader = LibraryLoader()
  92. if not swigModuleName in sys.modules: module = loader.load(swigModuleName)
  93. # OK, now the modules on which this one depends are loaded and template-instantiated,
  94. # and the SWIG module for this one is also loaded.
  95. # We're going to put the things we load and create in two places: the optional
  96. # 'namespace' parameter, and the this_module variable's namespace.
  97. # make a new 'swig' sub-module for this_module. Also look up or create a
  98. # different 'swig' module for 'namespace'. Since 'namespace' may be used to
  99. # collect symbols from multiple different ITK modules, we don't want to
  100. # stomp on an existing 'swig' module, nor do we want to share 'swig' modules
  101. # between this_module and namespace.
  102. this_module.swig = imp.new_module('swig')
  103. if namespace is not None: swig = namespace.setdefault('swig', imp.new_module('swig'))
  104. for k, v in module.__dict__.items():
  105. if not k.startswith('__'): setattr(this_module.swig, k, v)
  106. if namespace is not None and not k.startswith('__'): setattr(swig, k, v)
  107. data = module_data[name]
  108. if data:
  109. for template in data['templates']:
  110. if len(template) == 4:
  111. # this is a template description
  112. pyClassName, cppClassName, swigClassName, templateParams = template
  113. # It doesn't matter if an itkTemplate for this class name already exists
  114. # since every instance of itkTemplate with the same name shares the same
  115. # state. So we just make a new instance and add the new templates.
  116. templateContainer = itkTemplate.itkTemplate(cppClassName)
  117. try:
  118. templateContainer.__add__(templateParams, getattr(module, swigClassName))
  119. setattr(this_module, pyClassName, templateContainer)
  120. if namespace is not None:
  121. current_value = namespace.get(pyClassName)
  122. if current_value != None and current_value != templateContainer:
  123. DebugPrintError("Namespace already has a value for %s, which is not an itkTemplate instance for class %s. Overwriting old value." %(pyClassName, cppClassName))
  124. namespace[pyClassName] = templateContainer
  125. except Exception, e:
  126. DebugPrintError("%s not loaded from module %s because of exception:\n %s" %(swigClassName, name, e))
  127. else:
  128. # this is a description of a non-templated class
  129. pyClassName, cppClassName, swigClassName = template
  130. try:
  131. swigClass = getattr(module, swigClassName)
  132. itkTemplate.registerNoTpl(cppClassName, swigClass)
  133. setattr(this_module, pyClassName, swigClass)
  134. if namespace is not None:
  135. current_value = namespace.get(pyClassName)
  136. if current_value != None and current_value != swigClass:
  137. DebugPrintError("Namespace already has a value for %s, which is not class %s. Overwriting old value." %(pyClassName, cppClassName))
  138. namespace[pyClassName] = swigClass
  139. except Exception, e:
  140. DebugPrintError("%s not found in module %s because of exception:\n %s" %(swigClassName, name, e))
  141. if itkConfig.ImportCallback: itkConfig.ImportCallback(name, 1)
  142. def DebugPrintError(error):
  143. if itkConfig.DebugLevel == itkConfig.WARN:
  144. print >> sys.stderr, error
  145. elif itkConfig.DebugLevel == itkConfig.ERROR:
  146. raise RuntimeError(error)
  147. class LibraryLoader(object):
  148. """Do all the work to set up the environment so that a SWIG-generated library
  149. can be properly loaded. This invloves setting paths, etc., defined in itkConfig."""
  150. # To share symbols across extension modules, we must set
  151. # sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)
  152. #
  153. # Since RTLD_NOW==0x002 and RTLD_GLOBAL==0x100 very commonly
  154. # we will just guess that the proper flags are 0x102 when there
  155. # is no dl module. On darwin (where there is not yet a dl module)
  156. # we need different flags because RTLD_GLOBAL = 0x008.
  157. darwin_dlopenflags = 0xA
  158. generic_dlopenflags = 0x102
  159. if sys.platform.startswith('darwin'):
  160. dlopenflags = darwin_dlopenflags
  161. elif sys.platform.startswith('win'):
  162. dlopenflags = None
  163. else:
  164. dlopenflags = generic_dlopenflags
  165. # now try to refine the dlopenflags if we have a dl module.
  166. try:
  167. import dl
  168. dlopenflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
  169. except:
  170. pass
  171. def setup(self):
  172. self.old_cwd = os.getcwd()
  173. try:
  174. os.chdir(itkConfig.swig_lib)
  175. except OSError:
  176. # silently pass to avoid the case where the dir is not there
  177. pass
  178. self.old_path = sys.path
  179. sys.path = [itkConfig.swig_lib, itkConfig.swig_py] + sys.path
  180. try:
  181. self.old_dlopenflags = sys.getdlopenflags()
  182. sys.setdlopenflags(self.dlopenflags)
  183. except:
  184. self.old_dlopenflags = None
  185. def load(self, name):
  186. self.setup()
  187. try:
  188. fp = None # needed in case next line raises exception, so that finally block works
  189. fp, pathname, description = imp.find_module(name)
  190. return imp.load_module(name, fp, pathname, description)
  191. finally:
  192. # Since we may exit via an exception, close fp explicitly.
  193. if fp: fp.close()
  194. self.cleanup()
  195. def cleanup(self):
  196. os.chdir(self.old_cwd)
  197. sys.path = self.old_path
  198. if self.old_dlopenflags:
  199. try: sys.setdlopenflags(self.old_dlopenflags)
  200. except: pass
  201. # Make a list of all know modules (described in *Config.py files in the
  202. # config_py directory) and load the information described in those Config.py
  203. # files.
  204. dirs = [p for p in itkConfig.path if os.path.isdir(p)]
  205. module_data = {}
  206. for d in dirs:
  207. known_modules = [f[:-9] for f in os.listdir(d+os.sep+"Configuration") if f.endswith('Config.py')]
  208. known_modules.sort()
  209. sys.path.append(d)
  210. sys.path.append(d+os.sep+".."+os.sep+"lib")
  211. for module in known_modules:
  212. data = {}
  213. execfile(os.path.join(d+os.sep+"Configuration", module + 'Config.py'), data)
  214. module_data[module] = data