-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimporter.py
More file actions
39 lines (28 loc) · 972 Bytes
/
importer.py
File metadata and controls
39 lines (28 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 1 11:54:40 2021
@author: maherme
"""
import os.path
import types
import sys
print('Running importer.py')
def import_(module_name, module_file, module_path):
if module_name in sys.modules:
return sys.modules[module_name]
module_rel_file_path = os.path.join(module_path, module_file)
module_abs_file_path = os.path.abspath(module_rel_file_path)
# read source code from file
with open(module_rel_file_path, 'r') as code_file:
source_code = code_file.read()
# create a module object
mod = types.ModuleType(module_name)
mod.__file__ = module_abs_file_path
# set a ref in sys.modules
sys.modules[module_name] = mod
# compile source code
code = compile(source_code, filename=module_abs_file_path, mode='exec')
# execute compiled source code
exec(code, mod.__dict__)
return sys.modules[module_name]