Getting a module's byte code, how?

Steve Holden steve at holdenweb.com
Wed Feb 2 17:33:35 EST 2005


Irmen de Jong wrote:

> Mark Nenadov wrote:
> 
>> On Wed, 02 Feb 2005 23:03:17 +0100, Irmen de Jong wrote:
>>
>>
>>> What would be the best way, if any, to obtain
>>> the bytecode for a given loaded module?
>>>
>>> I can get the source:
>>> import inspect
>>> import os
>>> src = inspect.getsource(os)
>>>
>>> but there is no ispect.getbytecode()  ;-)
>>>
>>> --Irmen
>>
>>
>>
>> The inspect API documentation says that code objects have "co_code", 
>> which
>> is a string of raw compiled bytecode.
>>
>> Hope that helps!
> 
> 
> Not very much, sorry. Because we now changed the problem into:
> "how to obtain the code object from a module".
> 
> 
> Perhaps a bit of background is in order.
> For Pyro, I'm sending module byte codes across the
> wire if the other side needs it (the mobile code feature).
> However, this only works for modules that can be loaded
> from a file on disk (because I'm now reading the .pyc file
> that belongs to the module). When the receiving end in turn
> calls another Pyro object, it may have to send the module's
> bytecode again-- but that is no longer possible because the
> module has no associated file anymore! (It is considered to
> be a builtin module)
> But because it is *loaded*, there must be some way to get
> to the bytecodes, right?
> 
I'm not sure why you think the module's code would be needed once it's 
been executed. That assigns all necessary code blocks to the functions 
defined therein, so the code, once the import has been executed, is 
garbage (from the interpreter's rather process-centric view of things).

The module will, however, have a __file__ attribute, which should allow 
you to retrieve the code as mentioned in my previous post - a .pyc file, 
it appears, is just a four-byte magic number, a four-byte timestamp and 
a marshalled code object.

Of course there's no guarantee that the module has been loaded from a 
compiled file. In that case your only option is to read in the source 
and compile it.

I am presuming that this feature of Pyro won't allow a 2.3 system to 
talk to a 2.4 one, since the byte codes are incompatible.

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005          http://www.python.org/pycon/2005/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list