Skip to content

Instantly share code, notes, and snippets.

@Infinitusvoid
Last active August 30, 2023 21:24
Show Gist options
  • Save Infinitusvoid/bafe6a7249f68f287b6c8db319c41190 to your computer and use it in GitHub Desktop.
Save Infinitusvoid/bafe6a7249f68f287b6c8db319c41190 to your computer and use it in GitHub Desktop.
Python : How to load and import code form file ?
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()
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