Last active
August 30, 2023 21:24
-
-
Save Infinitusvoid/bafe6a7249f68f287b6c8db319c41190 to your computer and use it in GitHub Desktop.
Python : How to load and import code form file ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def execute_file_content(file_path): | |
if file_path: | |
with open(file_path, 'r') as file: | |
code = compile( file.read(), file_path, 'exec') | |
exec(code, globals()) | |
print("loaded :", file_path) | |
execute_file_content(r"C:\Users\x\my_module.py") | |
#some_func() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import importlib.util | |
# Add the path to the module's directory | |
module_path = r"C:\x\x" | |
module_name = "my_module" # The name of your module (without the .py extension) | |
# Load the module from the specified path | |
spec = importlib.util.spec_from_file_location(module_name, module_path + "\\" + module_name + ".py") | |
my_module = importlib.util.module_from_spec(spec) | |
sys.modules.pop(module_name, None) # Remove the module from sys.modules to enable reload | |
spec.loader.exec_module(my_module) | |
print(dir(my_module)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment