importer.py revision 13671:b288ca1bcae8
1# Copyright (c) 2008 The Hewlett-Packard Development Company
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Nathan Binkert
28
29# Simple importer that allows python to import data from a dict of
30# code objects.  The keys are the module path, and the items are the
31# filename and bytecode of the file.
32class CodeImporter(object):
33    def __init__(self):
34        self.modules = {}
35
36    def add_module(self, filename, abspath, modpath, code):
37        if modpath in self.modules:
38            raise AttributeError("%s already found in importer" % modpath)
39
40        self.modules[modpath] = (filename, abspath, code)
41
42    def find_module(self, fullname, path):
43        if fullname in self.modules:
44            return self
45
46        return None
47
48    def load_module(self, fullname):
49        # Because the importer is created and initialized in its own
50        # little sandbox (in init.cc), the globals that were available
51        # when the importer module was loaded and CodeImporter was
52        # defined are not available when load_module is actually
53        # called. Soooo, the imports must live here.
54        import imp
55        import os
56        import sys
57
58        try:
59            mod = sys.modules[fullname]
60        except KeyError:
61            mod = imp.new_module(fullname)
62            sys.modules[fullname] = mod
63
64        try:
65            mod.__loader__ = self
66            srcfile,abspath,code = self.modules[fullname]
67
68            override = os.environ.get('M5_OVERRIDE_PY_SOURCE', 'false').lower()
69            if override in ('true', 'yes') and  os.path.exists(abspath):
70                src = open(abspath, 'r').read()
71                code = compile(src, abspath, 'exec')
72
73            if os.path.basename(srcfile) == '__init__.py':
74                mod.__path__ = fullname.split('.')
75                mod.__package__ = fullname
76            else:
77                mod.__package__ = fullname.rpartition('.')[0]
78            mod.__file__ = srcfile
79
80            exec(code, mod.__dict__)
81        except Exception:
82            del sys.modules[fullname]
83            raise
84
85        return mod
86
87# Create an importer and add it to the meta_path so future imports can
88# use it.  There's currently nothing in the importer, but calls to
89# add_module can be used to add code.
90import sys
91importer = CodeImporter()
92add_module = importer.add_module
93sys.meta_path.append(importer)
94