PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/Wrapping/Generators/Python/itkBase.py

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