In Windows programming, sometimes we often need to use some unconventional methods, such as loading the DLL from the memory and then using the functions in the DLL. So I thought about whether to combine several compiled Pyc files into one when using Python, then read the file dynamically, and divide the files according to the tag, obtain the pyc content of different modules and dynamically reference them to our program as a new module. This involves a problem: how to integrate a pyc into the memory, then, it is retrieved from the memory and converted into a new module for introduction. After finding some materials, I found that one method is to process the code object PyCodeObject, that is, the compiled content after compile, and then read and form the codeobject object, use types. moduleType creates a new module, and then adds the new module to sys. go to the modules dictionary and then execute the previously read codeObject object in the newly created Module Environment. You can use this new import module for a long time, as follows:
PycContext = open(, PyCodeObject = marshal.loads(b[8newModule = types.ModuleType(] = c newModule.
The code for recording a foreign document is as follows:
load_compiled_from_memory(name, filename, data, ispackage= data[:4]!= ImportError( % code = marshal.loads(data[8 == mod = filename = [name.replace(, code mod. mod
In addition, the compiled files automatically generated using Python import generally contain magic numbers and timestamps. That is to say, you need to move 8 bits when reading codeObject, however, some APIs using Python do not necessarily contain the magic number and timestamp. In this case, you do not need to shift and directly read the generated codeobject.
Foreign references