简体   繁体   中英

Force python to ignore pyc files when dynamically loading modules from filepaths

I need to import python modules by filepath (eg, "/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)

load_source does the right thing for me, ie

dir, name = os.path.split(path)
mod = imp.load_source(name, path)

uses the .py variant even if a pyc file is available - name ends in .py under python3. The obvious solution is obviously to delete all .pyc files before loading the file - the race condition may be a problem though if you run more than one instance of your program.

One other possibility: Iirc you can let python interpret files from memory - ie load the file with the normal file API and then compile the in-memory variant. Something like:

path = "some Filepath.py"
with open(path, "r", encoding="utf-8") as file:
    data = file.read()
exec(compile(data, "<string>", "exec")) # fair use of exec, that's a first!

How about using zip files containing python sources instead:

import sys
sys.path.insert("package.zip")

您可以将包含.py文件的目录标记为只读。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM