Skip to content

Instantly share code, notes, and snippets.

@quartox
Created July 20, 2016 17:00
Show Gist options
  • Save quartox/e15d87775650ce4c0045ae449d9e903d to your computer and use it in GitHub Desktop.
Save quartox/e15d87775650ce4c0045ae449d9e903d to your computer and use it in GitHub Desktop.
def import_module(file_name):
"""Import the file (including optional relative or absolute path) into
a module namespace.
Args:
file_name - A string with the name of the file to load as a module.
Returns:
The module namespace.
"""
path = file_name.rfind("/")
file_suffix = file_name.find(".")
module_name = file_name[path + 1:file_suffix]
try:
spec = importlib.util.spec_from_file_location(
module_name, file_name)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except OSError as e:
print("Error loading", file_name, "with error message:", e.strerror)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment