2 # Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved
3 # Copyright (c) 2019 Pantheon.tech. All rights reserved
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Copied and updated for python3 from cloudify-python-importer
19 from __future__ import print_function
27 import __builtin__ as builtins
30 class _OurImporter(object):
32 def __init__(self, dir_name, load_file):
33 self.dirname = dir_name
34 self.load_file = load_file
36 def load_module(self, package_name):
38 return sys.modules[package_name]
44 fp, pathname, description = imp.find_module(
45 package_name.split(".")[-1],
46 ["/".join(self.dirname.split("/")[:-1])]
48 m = imp.load_module(package_name, fp, pathname, description)
49 except ImportError as e:
52 m = imp.new_module(package_name)
54 m.__name__ = package_name
55 m.__path__ = [self.dirname]
60 sys.modules.setdefault(package_name, m)
64 class _OurFinder(object):
66 def __init__(self, dir_name):
67 self.dir_name = dir_name
69 def find_module(self, package_name):
70 real_path = "/".join(package_name.split("."))
72 for path in [self.dir_name] + sys.path:
74 full_name = os.path.abspath(path) + "/" + real_path
75 dir_root = os.path.abspath(path) + "/" + real_path.split("/")[0]
77 if os.path.isfile(path + "/" + real_path + ".py"):
78 return _OurImporter(full_name, True)
80 if os.path.isdir(full_name):
81 if not os.path.isfile(dir_root + "/" + "__init__.py"):
82 print('Creating __init__.py in', dir_root, file=sys.stderr)
83 with open(dir_root + "/" + "__init__.py", 'a+') as file:
84 file.write("# Created by importer")
85 return _OurImporter(dir_root, False)
87 return _OurImporter(full_name, True)
92 def _check_import(dir_name):
93 return _OurFinder(dir_name)
96 def register_callback():
97 sys.path_hooks.append(_check_import)
99 save_import = builtins.__import__
101 def new_import(*argv, **kwargs):
103 module = save_import(*argv, **kwargs)
104 except ImportError as e:
105 finder = _OurFinder("")
108 importer = finder.find_module(argv[0])
111 module = importer.load_module(argv[0])
117 builtins.__import__ = new_import