I need to import python modules by filepath (e.g., "/some/path/to/module.py") known only at runtime and ignore any .pyc
files should they exist.
This previous question suggests the use of imp.load_module
as a solution but this approach also appears to use a .pyc
version if it exists.
importme.py
SOME_SETTING = 4
main.py:
import imp
if __name__ == '__main__':
name = 'importme'
openfile, pathname, description = imp.find_module(name)
module = imp.load_module(name, openfile, pathname, description)
openfile.close()
print module
Executing twice, the .pyc
file is used after first invocation:
$ python main.py
<module 'importme' from '/Users/dbryant/temp/pyc/importme.py'>
$ python main.py
<module 'importme' from '/Users/dbryant/temp/pyc/importme.pyc'>
Unfortunately, imp.load_source
has the same behavior (from the docs):
Note that if a properly matching byte-compiled file (with suffix .pyc or .pyo) exists, it will be used instead of parsing the given source file.
Making every script-containing directory read-only is the only solution that I know of (prevents generation of .pyc
files in the first place) but I would rather avoid it if possible.
(note: using python 2.7)