Can anyone show me an example of of using dis() with a traceback?
Examples of using disassemble_str ing() and distb() separately if
possible would be nice also.
I'm experimenting with modifying the dis module so that it returns it's
results instead of using 'print' it as it goes. I want to make sure it
works for all the current use cases (or as many as possible), but I
haven't been able to find any examples of using dis with tracebacks
using google. I keep getting various copies of the current and older
Python doc pages when I search, and not much else.
How much other python code depends on the dis() and disassembly()
functions? Is it used by other modules or is it meant to be a stand
alone tool?
The changes I've made (for my own use so far) is to have disassembly()
return a bare unformatted table, (list of list), that can easily be
examined with python, and then to use a dis2str() function to return a
nice formatted output-string from the table. In order to have dis()
display properly in an interactive shell as well as printing, I have
dis() return a disassembly list object with a __repr__() method to call
dis2str().
class disobj(list):
""" A disassembly list object """
def __init__(self, dislist, name=None, lasti=-1):
self[:] = dislist
self.name = name
self.lasti = lasti
def __repr__(self):
return dis2str(self, self.name, self.lasti)
That seems to work well in both the shell and with 'print'. And it
still allows direct table introspection without having to parse the
output. ;-)
For example the get_labels() function used was reduced to ...
def getlabels(disli st):
""" Get labels from disassembly list table. """
return [x[4] for x in dislist if type(x[4]) is str]
Another benefit, is to be able to get the results without having to
redirect, capture, and then reset sys.stdout.
But I still need to rewrite disassemble_str ing() and need to test it
with tracebacks.
Cheers,
Ron 5 2343
Ron Adam wrote: Can anyone show me an example of of using dis() with a traceback?
Examples of using disassemble_str ing() and distb() separately if possible would be nice also.
[cliped]
But I still need to rewrite disassemble_str ing() and need to test it with tracebacks.
Cheers, Ron
It seems I've found a bug in dis.py, or maybe a expected non feature.
When running dis from a program it fails to find the last traceback
because sys.last_traceb ack doesn't get set. (a bug in sys?) It works
ok from the shell, but not from the program.
Changing it to to get sys.exc_info()[2], fix's it in a program, but then
it doesn't work in the shell. So I replaced it with the following which
works in both.
try:
if hasattr(sys,'la st_traceback'):
tb = sys.last_traceb ack
else:
tb = sys.exc_info()[2]
except AttributeError:
raise RuntimeError, "no last traceback to disassemble"
I'm still looking for info on how to use disassemble_str ing().
Cheers,
Ron
On Sun, 09 Oct 2005 12:10:46 GMT, Ron Adam <rr*@ronadam.co m> wrote: Ron Adam wrote: Can anyone show me an example of of using dis() with a traceback?
Examples of using disassemble_str ing() and distb() separately if possible would be nice also.
[cliped]
But I still need to rewrite disassemble_str ing() and need to test it with tracebacks.
Cheers, Ron
It seems I've found a bug in dis.py, or maybe a expected non feature. When running dis from a program it fails to find the last traceback because sys.last_traceb ack doesn't get set. (a bug in sys?) It works ok from the shell, but not from the program.
Changing it to to get sys.exc_info()[2], fix's it in a program, but then it doesn't work in the shell. So I replaced it with the following which works in both.
try: if hasattr(sys,'la st_traceback'): tb = sys.last_traceb ack else: tb = sys.exc_info()[2] except AttributeError: raise RuntimeError, "no last traceback to disassemble"
I'm still looking for info on how to use disassemble_str ing().
One way to get dis output without modufying dis is to capture stdout:
(ancient thing I cobbled together, no guarantees ;-) class SOCapture:
... """class to capture stdout between calls to start & end methods, q.v."""
... import sys
... def __init__(self):
... self.so = self.sys.stdout
... self.text = []
... def start(self, starttext=None) :
... """Override s sys.stdout to capture writes.
... Optional starttext is immediately appended as if written to stdout."""
... self.sys.stdout = self
... if starttext is None: return
... self.text.appen d(starttext)
... def end(self, endtext=None):
... """Restores stdout to value seen at contruction time.
... Optional endtext is appended as if written to stdout before that."""
... self.sys.stdout = self.so
... if endtext is None: return
... self.text.appen d(endtext)
... def gettext(self):
... """Returns captured text as single string."""
... return ''.join(self.te xt)
... def clear(self):
... """Clears captured text list."""
... self.text = []
... def write(self, s):
... """Appends written string to captured text list.
... This method is what allows an instance to stand in for stdout."""
... self.text.appen d(s)
... def foo(x): return (x+1)**2
... so = SOCapture() import dis so.start() dis.dis(foo) so.end() print so.gettext()
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 LOAD_CONST 2 (2)
10 BINARY_POWER
11 RETURN_VALUE
Or safer:
def diss(code):
... try:
... so = SOCapture()
... so.start()
... dis.dis(code)
... finally:
... so.end()
... return so.gettext()
... diss(foo)
' 1 0 LOAD_FAST 0 (x)\n 3 LOAD_CONST 1 (1)\
n 6 BINARY_ADD \n 7 LOAD_CONST 2 (2)\n
10 BINARY_POWER \n 11 RETURN_VALUE \n' print diss(foo)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 LOAD_CONST 2 (2)
10 BINARY_POWER
11 RETURN_VALUE
Regards,
Bengt Richter I'm still looking for info on how to use disassemble_str ing().
How about this? import dis def f():
... print "hello world"
... f.func_code.co_ code
'd\x01\x00GHd\x 00\x00S' dis.disassemble _string(f.func_ code.co_code)
0 LOAD_CONST 1 (1)
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (0)
8 RETURN_VALUE
Skip
Bengt Richter wrote: On Sun, 09 Oct 2005 12:10:46 GMT, Ron Adam <rr*@ronadam.co m> wrote: Ron Adam wrote:
It seems I've found a bug in dis.py, or maybe a expected non feature. When running dis from a program it fails to find the last traceback because sys.last_traceb ack doesn't get set. (a bug in sys?) It works ok from the shell, but not from the program.
Changing it to to get sys.exc_info()[2], fix's it in a program, but then it doesn't work in the shell. So I replaced it with the following which works in both.
try: if hasattr(sys,'la st_traceback'): tb = sys.last_traceb ack else: tb = sys.exc_info()[2] except AttributeError: raise RuntimeError, "no last traceback to disassemble"
I guess I should do a bug report on this part so you can do the
following in a program.
try:
(something that fails)
except:
dis.dis() # print a dissasembled traceback.
I'm still looking for info on how to use disassemble_str ing().
One way to get dis output without modufying dis is to capture stdout: (ancient thing I cobbled together, no guarantees ;-) >>> class SOCapture: ... """class to capture stdout between calls to start & end methods, q.v.""" ... import sys ... def __init__(self): ... self.so = self.sys.stdout ... self.text = [] ... def start(self, starttext=None) : ... """Override s sys.stdout to capture writes. ... Optional starttext is immediately appended as if written to stdout.""" ... self.sys.stdout = self ... if starttext is None: return ... self.text.appen d(starttext) ... def end(self, endtext=None): ... """Restores stdout to value seen at contruction time. ... Optional endtext is appended as if written to stdout before that.""" ... self.sys.stdout = self.so ... if endtext is None: return ... self.text.appen d(endtext) ... def gettext(self): ... """Returns captured text as single string.""" ... return ''.join(self.te xt) ... def clear(self): ... """Clears captured text list.""" ... self.text = [] ... def write(self, s): ... """Appends written string to captured text list. ... This method is what allows an instance to stand in for stdout.""" ... self.text.appen d(s)
This is useful. But I've already rewritten it. ;-)
I tried to keep it's output as close to the original as possible. For
example replacing the the call "dis.dis(fu nc)" in test_dis.py with
"print dis.dis(func)" is all that's needed to get it to pass the test.
s = StringIO.String IO()
save_stdout = sys.stdout
sys.stdout = s
dis.dis(func) #<- "print dis.dis(func)" passes
sys.stdout = save_stdout
got = s.getvalue()
The above could be replaced with...
got = dis.dis(func)
The same minor change needs to be made in test_peepholer. py. It uses
dis to check the bytecodes. I havn't found any other dependancies yet. >>> diss(foo) ' 1 0 LOAD_FAST 0 (x)\n 3 LOAD_CONST 1 (1)\ n 6 BINARY_ADD \n 7 LOAD_CONST 2 (2)\n 10 BINARY_POWER \n 11 RETURN_VALUE \n' >>> print diss(foo) 1 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (1) 6 BINARY_ADD 7 LOAD_CONST 2 (2) 10 BINARY_POWER 11 RETURN_VALUE
This is something I fixed (or added) so it displays the same from print,
the terminal, and the command line.
I'm not sure if it can replace dis module. It may be different enough
that it can't. I suspect some might not like the table class. I'm
thinking of making a bug report for the traceback not being found when
distb() is used inline, and attach the altered file for consideration
and feedback.
One possibility is to dispense with keeping it like dis and rename it to
something different and then additional functions and capabilities can
be added to it without worrying about breaking anything. ;-)
BTW do you know how to read the time and version stamp of the beginning
of .pyo and .pyc files? I added that (just too easy not to) and would
like to put the time and version stamp at the top of the output for
those. It's easy to take stuff out if needed. ;-)
I can send it to you as an attached file if you'd like to take a look.
Cheers,
Ron sk**@pobox.com wrote: >> I'm still looking for info on how to use disassemble_str ing(). How about this? >>> import dis >>> def f(): ... print "hello world" ... >>> f.func_code.co_ code 'd\x01\x00GHd\x 00\x00S' >>> dis.disassemble _string(f.func_ code.co_code) 0 LOAD_CONST 1 (1) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (0) 8 RETURN_VALUE
Skip
Thanks Skip, I had figured it out, but I like your example. import dis dis.dis('d\x01\ x00GHd\x00\x00S ')
0 LOAD_CONST 1 (1)
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (0)
8 RETURN_VALUE
It works! :-)
Cheers,
Ron This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Mohammed Mazid |
last post by:
Can anyone please help me on how to move to the next and previous
question?
Here is a snippet of my code:
Private Sub cmdNext_Click()
End Sub
Private Sub cmdPrevious_Click()
showrecord
|
by: Stevey |
last post by:
I have the following XML file...
<?xml version="1.0"?>
<animals>
<animal>
<name>Tiger</name>
<questions>
<question index="0">true</question>
<question index="1">true</question>
</questions>
|
by: nospam |
last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types,
so, since it seems to me that Partial Types is still in the design or
development stages at Microsoft, I am going to ask it differently.
FOUR QUESTIONS:
The background:
I got three (3) files
|
by: Ekqvist Marko |
last post by:
Hi,
I have one Access database table including questions and answers. Now
I need to give answer id automatically to questionID column. But I
don't know how it is best (fastest) to do?
table before
rowID answID qryrow questionID datafield
1591 12 06e 06e 06e question
1593 12 06f 06f 06f question
1594 12 answer to the question 06f
|
by: glenn |
last post by:
I am use to programming in php and the way session and post vars are past
from fields on one page through to the post page automatically where I can
get to their values easily to write to a database or continue to process on
to the next page.
I am now trying to learn ASP to see if we can replace some of our
applications that were written in php with an ASP alternative. However,
after doing many searches on google and reading a couple...
| |
by: Rider |
last post by:
Hi, simple(?) question about asp.net configuration..
I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm
first start application the follow message shown.
=========
Server Error in '/QuickStartv20' Application.
--------------------------------------------------------------------------------
Configuration Error
Description: An error occurred during the processing of a configuration file
|
by: Jeff |
last post by:
In the function below, can size ever be 0 (zero)?
char *clc_strdup(const char * CLC_RESTRICT s)
{
size_t size;
char *p;
clc_assert_not_null(clc_strdup, s);
size = strlen(s) + 1;
|
by: spibou |
last post by:
In the statement "a *= expression" is expression assumed to be
parenthesized ? For example if I write "a *= b+c" is this the same
as "a = a * (b+c)" or "a = a * b+c" ?
|
by: Allan Ebdrup |
last post by:
Hi,
I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix
question is a question where you have several options that can all be rated
according to several possible ratings (from less to more for example).
I have a question object that has two properties that contain the
collections Options and Ratings.
now I want this kind of layout:
---
Rating1 Rating2 Rating3
Option 1 () () ...
|
by: Zhang Weiwu |
last post by:
Hello!
I wrote this:
..required-question p:after {
content: "*";
}
Corresponding HTML:
<div class="required-question"><p>Question Text</p><input /></div>
<div class="not-required-question"><p>Question Text</p><input /></div>
|
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,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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,...
|
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...
|
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...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |