Force python to ignore pyc files when dynamically loading modules from file paths

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)

+4
source share
3 answers

load_source does what I need for me, i.e.

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

uses the .py option, even if the pyc file is available - the name ends with .py in python3. The obvious solution is to obviously delete all .pyc files before downloading the file. A race condition can be a problem, although if you run more than one instance of your program.

Another possibility: Iirc, you can let python interpret files from memory - that is, load a file with the regular file API and then compile the memory option. Sort of:

 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 a first! 
+2
source

How to use instead zip files containing python sources:

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

You can mark directories containing .py files as read-only.

0
source

Source: https://habr.com/ru/post/1385197/


All Articles