473,394 Members | 1,759 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

dis.dis question


Can anyone show me an example of of using dis() with a traceback?

Examples of using disassemble_string() 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(dislist):
""" 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_string() and need to test it
with tracebacks.

Cheers,
Ron

Oct 8 '05 #1
5 2318
Ron Adam wrote:

Can anyone show me an example of of using dis() with a traceback?

Examples of using disassemble_string() and distb() separately if
possible would be nice also.
[cliped]
But I still need to rewrite disassemble_string() 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_traceback 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,'last_traceback'):
tb = sys.last_traceback
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_string().

Cheers,
Ron


Oct 9 '05 #2
On Sun, 09 Oct 2005 12:10:46 GMT, Ron Adam <rr*@ronadam.com> wrote:
Ron Adam wrote:

Can anyone show me an example of of using dis() with a traceback?

Examples of using disassemble_string() and distb() separately if
possible would be nice also.


[cliped]
But I still need to rewrite disassemble_string() 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_traceback 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,'last_traceback'):
tb = sys.last_traceback
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_string().


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):
... """Overrides 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.append(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.append(endtext)
... def gettext(self):
... """Returns captured text as single string."""
... return ''.join(self.text)
... 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.append(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
Oct 16 '05 #3
I'm still looking for info on how to use disassemble_string().
How about this?
import dis
def f(): ... print "hello world"
... f.func_code.co_code 'd\x01\x00GHd\x00\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
Oct 16 '05 #4
Bengt Richter wrote:
On Sun, 09 Oct 2005 12:10:46 GMT, Ron Adam <rr*@ronadam.com> 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_traceback 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,'last_traceback'):
tb = sys.last_traceback
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_string().

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):
... """Overrides 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.append(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.append(endtext)
... def gettext(self):
... """Returns captured text as single string."""
... return ''.join(self.text)
... 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.append(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(func)" in test_dis.py with
"print dis.dis(func)" is all that's needed to get it to pass the test.

s = StringIO.StringIO()
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

Oct 16 '05 #5
sk**@pobox.com wrote:
>> I'm still looking for info on how to use disassemble_string().
How about this?
>>> import dis
>>> def f(): ... print "hello world"
... >>> f.func_code.co_code 'd\x01\x00GHd\x00\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


Oct 16 '05 #6

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

Similar topics

1
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
3
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>
7
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...
3
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...
10
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...
10
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...
53
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;
56
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" ?
2
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...
3
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
Oralloy
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.