2 # Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved
3 # Copyright (c) 2019 Pantheon.tech. All rights reserved
4 # Copyright (c) 2020 AT&T Intellectual Property. All rights reserved
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
18 # Copied and updated for python3 from cloudify-python-importer
20 from __future__ import print_function
28 import __builtin__ as builtins
31 class _OurImporter(object):
33 def __init__(self, dir_name, load_file):
34 self.dirname = dir_name
35 self.load_file = load_file
37 def load_module(self, package_name):
39 return sys.modules[package_name]
45 fp, pathname, description = imp.find_module(
46 package_name.split(".")[-1],
47 ["/".join(self.dirname.split("/")[:-1])]
49 m = imp.load_module(package_name, fp, pathname, description)
50 except ImportError as e:
53 m = imp.new_module(package_name)
55 m.__name__ = package_name
56 m.__path__ = [self.dirname]
61 sys.modules.setdefault(package_name, m)
65 class _OurFinder(object):
67 def __init__(self, dir_name):
68 self.dir_name = dir_name
70 def find_module(self, package_name):
71 real_path = "/".join(package_name.split("."))
73 for path in [self.dir_name] + sys.path:
75 full_name = os.path.abspath(path) + "/" + real_path
76 dir_root = os.path.abspath(path) + "/" + real_path.split("/")[0]
78 if os.path.isfile(path + "/" + real_path + ".py"):
79 return _OurImporter(full_name, True)
81 if os.path.isdir(full_name):
82 if not os.path.isfile(dir_root + "/" + "__init__.py"):
83 print('Creating __init__.py in', dir_root, file=sys.stderr)
84 with open(dir_root + "/" + "__init__.py", 'a+') as file:
85 file.write("# Created by importer")
86 return _OurImporter(dir_root, False)
88 return _OurImporter(full_name, True)
93 def _check_import(dir_name):
94 return _OurFinder(dir_name)
97 def register_callback():
98 sys.path_hooks.append(_check_import)
100 save_import = builtins.__import__
102 def new_import(*argv, **kwargs):
104 module = save_import(*argv, **kwargs)
105 except ImportError as e:
106 finder = _OurFinder("")
109 importer = finder.find_module(argv[0])
112 module = importer.load_module(argv[0])
118 builtins.__import__ = new_import