Getting a module's code object
Arnaud Delobelle
arnodel at gmail.com
Thu Aug 25 11:33:55 EDT 2011
On 25 August 2011 16:07, Peter Otten <__peter__ at web.de> wrote:
> Arnaud Delobelle wrote:
>
>> In Python 3, a function f's code object can be accessed via f.__code__.
>>
>> I'm interested in getting a module's code object,
[...]
>
> Taken from pkgutil.py:
>
> def read_code(stream):
> # This helper is needed in order for the PEP 302 emulation to
> # correctly handle compiled files
> import marshal
>
> magic = stream.read(4)
> if magic != imp.get_magic():
> return None
>
> stream.read(4) # Skip timestamp
> return marshal.load(stream)
This works fine, thanks a lot!
> Alternatively you can compile the source yourself:
>
> module = compile(source, filename, "exec")
I don't necessarily have access to the source file.
--
Arnaud
More information about the Python-list
mailing list