473,732 Members | 2,201 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a module's byte code, how?

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.getsour ce(os)

but there is no ispect.getbytec ode() ;-)

--Irmen
Jul 18 '05 #1
8 3952
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.getsour ce(os)

but there is no ispect.getbytec ode() ;-)

--Irmen


The inspect API documentation says that code objects have "co_code", which
is a string of raw compiled bytecode.

Hope that helps!

- -
Mark Nenadov
Python Byte Solutions
http://www.pythonbyte.com/
Jul 18 '05 #2
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.getsour ce(os)

but there is no ispect.getbytec ode() ;-)

--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?
--Irmen
Jul 18 '05 #3
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.getsour ce(os)

but there is no ispect.getbytec ode() ;-)

--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(m bc)
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/
Jul 18 '05 #4
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.getsour ce(os)

but there is no ispect.getbytec ode() ;-)

--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/
Jul 18 '05 #5
Steve Holden wrote:
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:
Yup. As I explained in the other message, this is basically
what I'm doing at the moment (with a few twists; it reads the .py
file if no .pyc is available).
But I also want the bytecode of modules that don't have a .pyc file,
possibly because they have already been 'dynamically' loaded from
another bytecode string ;-)

Now, I could ofcourse store the bytecode string that I started
with *inside* the module itself, in a special attribute or so.
This just occurred to me and I think it's a possible solution.
But the bytecodes must be stored by Python itself somewhere
already... because Python is able to execute my module... right?
I want them! :-)
Note that the ugly details *might* change, and that byte codes are
version-dependent.


I know, but this fact was not yet mentioned in the Pyro manual.
Thanks for reminding me, I'll add it.

--Irmen
Jul 18 '05 #6
Steve Holden wrote:
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).
Ah, ofcourse. Thanks for this insight.
I may have to rethink some of this...
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.


Correct. However, when you're not using mobile code (the default),
you're fine.

--Irmen
Jul 18 '05 #7
Irmen de Jong wrote:
Steve Holden wrote:
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:

Yup. As I explained in the other message, this is basically
what I'm doing at the moment (with a few twists; it reads the .py
file if no .pyc is available).
But I also want the bytecode of modules that don't have a .pyc file,
possibly because they have already been 'dynamically' loaded from
another bytecode string ;-)

Aah, right, I suspect in these cases (which *are* pretty far from the
ordinary run of things) you'd sometimes be up the creek without a paddle.
Now, I could ofcourse store the bytecode string that I started
with *inside* the module itself, in a special attribute or so.
This just occurred to me and I think it's a possible solution.
But the bytecodes must be stored by Python itself somewhere
already... because Python is able to execute my module... right?
Not necessarily. I've just been playing with importing modules from a
database. Here's the relevant extract from my load_module() function:

code, package, path = row # ... from the database
code = marshal.loads(c ode)
module = DBmodule(modnam e) # subclass of moduleType
sys.modules[modname] = module
module.__name__ = modname
module.__file__ = path # "db:%s" % modname
module.__loader __ = dbimporter
if package:
module.__path__ = ["*db*"]
exec code in module.__dict__
#print modname, "loaded:", module, "pkg:", package
return module

Note well that the module is essentially imported by executing its
bytecode in the context of the module's directory. From that point on
the module doesn't need access to its code - all its functions and
classes have been created, and the functions and methods reachable from
the module's __dict__ now have appropriate snippets of the byte code as
their own code objects.
I want them! :-)

Well I'm afraid there's no guarantee that they haven't already been
garbage collected, and stamping your foot isn't going to do any good :-)
Note that the ugly details *might* change, and that byte codes are
version-dependent.

I know, but this fact was not yet mentioned in the Pyro manual.
Thanks for reminding me, I'll add it.

--Irmen


A pleasure. Thanks for Pyro! (and thanks for reminding me indirectly
that I need to guard that execution of hte module's code against
exceptions).

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/
Jul 18 '05 #8
Steve Holden wrote:
But I also want the bytecode of modules that don't have a .pyc file,
possibly because they have already been 'dynamically' loaded from
another bytecode string ;-)
Aah, right, I suspect in these cases (which *are* pretty far from the
ordinary run of things) you'd sometimes be up the creek without a paddle.


I was afraid of that.
The whole mobile code stuff in Pyro is very powerful, for the
cases where it works and makes sense, I think.
However it is also fairly messy.
In the end perhaps it introduces more problems than it solves,
but its really nice to see it work for the simple cases :)

I want them! :-)

Well I'm afraid there's no guarantee that they haven't already been
garbage collected, and stamping your foot isn't going to do any good :-)


Heh, that was funny :D
A pleasure. Thanks for Pyro! (and thanks for reminding me indirectly
that I need to guard that execution of hte module's code against
exceptions).


Pyro happily throws these exceptions in your face.
Like I said, rather messy.

--Irmen
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2736
by: F. GEIGER | last post by:
py2exe and datetime -> No module named datetime I've begun to use the stdlib module datetime instead of my home brewn classes. Since then a py2exe app doesn't run anymore: Traceback (most recent call last): File "MainFrame.py", line 26, in ? File "Notebook.pyo", line 125, in ? File "NotebookPage_Activities.pyo", line 7, in ?
16
13826
by: Jacob H | last post by:
Hi there list, I'm a beginning programmer, so please correct me if any of the following assumptions are wrong. Suppose I have the decimal number 255. Since integers in Python are 32 bits, it would look like this in binary: 00000000 00000000 00000000 11111111
0
2303
by: Josiah Carlson | last post by:
Good day everyone, I have produced a patch against the latest CVS to add support for two new formatting characters in the struct module. It is currently an RFE, which I include a link to at the end of this post. Please read the email before you respond to it. Generally, the struct module is for packing and unpacking of binary data. It includes support to pack and unpack the c types: byte, char, short, long, long long, char, *, and...
0
5507
by: lglmi | last post by:
'********************START OF BAS MODULE******************** Option Explicit Private Type OSVERSIONINFO dwOSVersionInfoSize As Long dwMajorVersion As Long dwMinorVersion As Long dwBuildNumber As Long dwPlatformId As Long
42
4982
by: WindAndWaves | last post by:
Dear All Can you tell me why you use a class module??? Thank you Nicolaas ---
8
3983
by: Salad | last post by:
I designed a small app and I wanted to do a BrowseFolder (see http://www.mvps.org/access/api/api0002.htm), basically do a file open diaglog and select a directory/folder. The problem is that you can't specify the starting folder. Stephan Leban provided a neat solution that does allow me to browse using a starting folder. I am using A97 and it works fine. However, I put it onto a system that uses AccessXP. And it chokes on...
1
1342
by: les | last post by:
Hello, I get the error on refering to the function created in the module. I've tried to declare the module but it is not halping. Please let me know what I'm doing wrong. This is my declaration in the ASPX file: ---------------------------------------------------------------------------- ------------------------------ 'reference to the function
4
2723
by: http://www.visual-basic-data-mining.net/forum | last post by:
Hi Does anyone know how to stay connected to the server and at the same time i can pass the string to and from the module to the form..... What I want: I put the connection at the module..... 1)I can pass the string from the form to the module...
0
1065
by: bkriznar | last post by:
The problem could be reproduced like this: Web Service: public string HelloWorld(byte aB) { byte lB = aB; return "Hello World"; }
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.