Sunday, April 24, 2016

Python frozen modules __hello__ and __phello__

Under Python 2.7:
>>> import __hello__
Hello world...
>>> import __phello__
Hello world...
>>> import __phello__.spam
Hello world...

Under Python 3.x:
>>> import __hello__
Hello World!

If check a file of this modules the next result will be returned:
>>> __hello__.__file__

The byte-code of these modules (see Python' source file ./Python/frozen.c) is compiled into Python lib (python27.dll on Windows and on Linux).

To check whether the module is frozen it's possible to use imp.is_frozen:
>>> import imp
>>> imp.is_frozen('__hello__')
>>> imp.is_frozen('__phello__')
>>> imp.is_frozen('__phello__.spam')

It's also possible to get the code object of these modules and for example get the bytecode:
>>> imp.get_frozen_object('__phello__.spam').co_code

Or get the code object filename:
>>> imp.get_frozen_object('__hello__').co_filename
>>> imp.get_frozen_object('__phello__').co_filename
>>> imp.get_frozen_object('__phello__.spam').co_filename

To load a frozen module Python C API function PyImport_ImportFrozenModule is used.

No comments:

Post a Comment