I need to import python modules along the file path (for example, "/some/path/to/module.py"), known only at runtime, and ignore any .pyc
files if they exist.
This previous question suggests using imp.load_module
as a solution, but this approach also uses the .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
Running twice, after the first call, the .pyc
file is used:
$ 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):
Please note that if a correctly matched byte-compiled file (with the suffix .pyc or .pyo) exists, it will be used instead of parsing the given source file.
Creating each read-only script-containing directory is the only solution I know (prevents the generation of .pyc
files in the first place), but I would prefer to avoid it if possible.
(note: using python 2.7)
source share