Python uses compiled modules from memory

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.