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!

Unfortunately co_code is an attribute of code objects, and a module doesn't *have* a code object, as far as I know - when it's imported its bytecode is executed in the scope of the module directory, but no attempt is made to keep the code around thereafter: what would be the point?

Having said which, if the module was loaded from a .pyc file then the bytecode is available from that - take everything but the first eight bytes and use marshal.loads() to turn it back into a code object:

>>> mbc = file("/lib/python2.4/re.pyc", "rb").read()[8:]
>>> import marshal
>>> code = marshal.loads(mbc)
>>> code
<code object ? at 0xa085d60, file "/tmp/python.2568/usr/lib/python2.4/re.py", line 1>
>>>


Note that the ugly details *might* change, and that byte codes are version-dependent.

tadaaa-ly y'rs  - 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/
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to