-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
42 lines (30 loc) · 881 Bytes
/
main.py
File metadata and controls
42 lines (30 loc) · 881 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
40
41
42
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 1 11:37:49 2021
@author: maherme
"""
import os.path
import types
import sys
module_name = 'module1'
module_file = 'module1_source.py'
module_path = '.'
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__)
# DONE!
mod.hello()
import module1
module1.hello() # This will work because module1 is in sys.modules.