How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- slurm: use a control node also for computing
- Evil ctypes hack in python
Import package modules at runtime (Python recipe)
http://code.activestate.com/recipes/223972/
If your top-level module is not a file but is packaged as a directory with __init__.py, then the accepted solution almost works, but not quite. In Python 3.5+ the following code is needed (note the added line that begins with 'sys.modules'):
Without this line, when exec_module is executed, it tries to bind relative imports in your top level __init__.py to the top level module name -- in this case "mymodule". But "mymodule" isn't loaded yet so you'll get the error "SystemError: Parent module 'mymodule' not loaded, cannot perform relative import". So you need to bind the name before you load it. The reason for this is the fundamental invariant of the relative import system: "The invariant holding is that if you have sys.modules['spam'] and sys.modules['spam.foo'] (as you would after the above import), the latter must appear as the foo attribute of the former" as discussed here.
I believe you can use
imp.find_module()
andimp.load_module()
to load the specified module. You'll need to split the module name off of the path, i.e. if you wanted to load/home/mypath/mymodule.py
you'd need to do:...but that should get the job done.
The best way, I think, is from the official documentation (29.1. imp — Access the import internals):
quite simple way: suppose you want import file with relative path ../../MyLibs/pyfunc.py
But if you make it without a guard you can finally get a very long path
I made a package that uses
imp
for you. I call itimport_file
and this is how it's used:You can get it at:
http://pypi.python.org/pypi/import_file
or at
http://code.google.com/p/import-file/