Skip to content

Instantly share code, notes, and snippets.

@eferro
Created July 28, 2012 22:34
Show Gist options
  • Select an option

  • Save eferro/3195028 to your computer and use it in GitHub Desktop.

Select an option

Save eferro/3195028 to your computer and use it in GitHub Desktop.
Import a python file as module
#!/usr/bin/python
import sys
import imp
import os.path
def import_pythonfile_as_module(python_file_path):
file_name = os.path.basename(python_file_path)
module_name = os.path.splitext(file_name)[0]
new_module = imp.load_source(module_name,
python_file_path)
return new_module
def main():
module = import_pythonfile_as_module(sys.argv[1])
print module
print dir(module)
if __name__ == '__main__':
main()
@eferro

eferro commented Jul 28, 2012

Copy link
Copy Markdown
Author

python import_from_file.py ~/test.py

Import the python file (~/test.py) as module and return the module... Aka, example of dynamic load python modules from files.. useful for plugins systems or similar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment