473,811 Members | 2,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

exceptions, internals (introspection? )

ej

I'm trying to figure out how to get at some of the internal interpreter
state for exception handlers and debug statements in general.
I just read through Section 8 of the Python Tutorial. I see how to catch an
exception, and specify an optional argument to get ahold of the exception
itself. For example:

try:
{}['foo']
except Exception, x:
print "class of x =", x.__class__
print "type(x) =", type(x)
print "dir(x) =", dir(x)
If you don't handle an exception, the interpreter will quit and print a
stack trace. What I'm not seeing is how to handle the exception, but still
get the stack trace as a string so I could dump it to a log file or email it
or something.

I have often wondered how to get at other internals, such as the name of
the current function, file, line number I am in? The arguments to the
current function, etc. I browsed through the table of contents of both the
Library Reference & Language Reference. I see section 18. Python Language
Services. In browsing through that, I'm thinking "Oh man... this is way
more than I need - there's got to be an easier way." Nothing else is
jumping out at me. Can someone point me to some documentation on this
subject and/or provide some examples?

Thanks, :)
-ej
Nov 10 '05 #1
7 1768
"ej" <ej at wellkeeper com> writes:
I have often wondered how to get at other internals, such as the name of
the current function, file, line number I am in? The arguments to the
current function, etc.


It's messy. Look at sys.exc_info() and go from there.
Nov 10 '05 #2
"ej" <"ej atwellkeepercom "@bag.python.or g> wrote
try:
{}['foo']
except Exception, x:
print "class of x =", x.__class__
print "type(x) =", type(x)
print "dir(x) =", dir(x)

If you don't handle an exception, the interpreter will quit and print a
stack trace. What I'm not seeing is how to handle the exception, but still
get the stack trace as a string so I could dump it to a log file or email it
or something.


the second example on this page shows you how to do that:

http://effbot.org/librarybook/traceback

</F>

Nov 10 '05 #3
ej wrote:
I have often wondered how to get at other internals, such as the name of
the current function, file, line number I am in? The arguments to the
current function, etc.


Others have given you information on how to get at the stack trace. But
regarding getting at some of the other internals you are talking about:
import inspect
help(inspect)


Back to exceptions, you can also provide your own global exception handler by
overriding sys.excepthook (drop in your own function).

--
Paul McNett
http://paulmcnett.com
http://dabodev.com

Nov 10 '05 #4
ej
"Paul Rubin" <http://ph****@NOSPAM.i nvalid> wrote in message
news:7x******** ****@ruckus.bro uhaha.com...
It's messy. Look at sys.exc_info() and go from there.


Yeah, I think I am starting to see what you mean...
#! /usr/local/bin/python

import sys

try:
{}['foo']
except Exception, x:
print "class of x =", x.__class__
print "type(x) =", type(x)
print "dir(x) =", dir(x)

print
(type_, value_, traceback_) = sys.exc_info()
print "type_ =", type_
print "value_ =", value_
print "traceback_ =", traceback_
for key in dir(traceback_) :
print "traceback_ .%s =" % key, eval("traceback _.%s" % key)

print "dir(frame) = ", dir(traceback_. tb_frame)
ej@sand:~/src/python/exceptions> foo
class of x = exceptions.KeyE rror
type(x) = <type 'instance'>
dir(x) = ['__doc__', '__getitem__', '__init__', '__module__', '__str__',
'args']

type_ = exceptions.KeyE rror
value_ = 'foo'
traceback_ = <traceback object at 0x402e2e14>
traceback_.tb_f rame = <frame object at 0x8177b3c>
traceback_.tb_l asti = 18
traceback_.tb_l ineno = 6
traceback_.tb_n ext = None
dir(frame) = ['__class__', '__delattr__', '__doc__', '__getattribute __',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__' ,
'__repr__', '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code',
'f_exc_tracebac k', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti',
'f_lineno', 'f_locals', 'f_restricted', 'f_trace']

But at least that is something to go on. Thanks for your reply!

-ej
Nov 10 '05 #5
ej
"Fredrik Lundh" <fr*****@python ware.com> wrote in message
news:ma******** *************** *************** @python.org...
the second example on this page shows you how to do that:

http://effbot.org/librarybook/traceback


I am looking at it. Thanks for your prompt reply, Mr. Lundh! :)

-ej
Nov 10 '05 #6
"ej" <ej at wellkeeper com> writes:
for key in dir(traceback_) :
print "traceback_ .%s =" % key, eval("traceback _.%s" % key)
Don't use eval for this. Use getattr(traceba ck_, key).
traceback_.tb_f rame = <frame object at 0x8177b3c>
traceback_.tb_l asti = 18
traceback_.tb_l ineno = 6
traceback_.tb_n ext = None


Yeah. As /F mentioned, there's also a traceback module that parses
this stuff out for you.
Nov 10 '05 #7
ej wrote:
I have often wondered how to get at other internals, such as the name of
the current function, file, line number I am in? The arguments to the
current function, etc. I browsed through the table of contents of both the
Library Reference & Language Reference. I see section 18. Python Language
Services. In browsing through that, I'm thinking "Oh man... this is way
more than I need - there's got to be an easier way." Nothing else is
jumping out at me. Can someone point me to some documentation on this
subject and/or provide some examples?


Poke around IPython, which implements a pretty massive amount of functionality
in this direction. In particular, you want to read OInspect.py and ultraTB.py.

Cheers,

f

Nov 11 '05 #8

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

Similar topics

4
1737
by: Mark Nottingham | last post by:
From previous discussion it seems that it's not possible to raise new-style objects. Does this effectively mean that it's impossible to use anything with a metaclass as an exception? i.e., am I missing some nifty trick that would allow me to do this in the meantime? If not, does anyone anticipate this changing anytime soon? Cheers and thanks, 1. http://aspn.activestate.com/ASPN/Mail/Message/python-list/1095990
24
2505
by: mag31 | last post by:
Is there any way to find out if a particular .net function will throw an exception without first generating the exception? I am using structured exception handling i.e. try catch finally blocks with a top level catch all for Exception. However, I would like to be able to catch most .net exceptions when they are generated. I would then be able to generate a valuable exception message and do something about it!!! Hence the question above....
10
342
by: Eric | last post by:
I have been researching how exceptions and dynamic_cast work to determine if I will use either feature for a game-console application. I have a few pre-concieved notions and questions that I was hoping some people here could validate/answer. PRECONCEIVED NOTION #1: Common implementations of dynamic_cast<> (VC++, GCC) rely on the presence of type_info objects. The use of strcmp() instead of type_info pointer-equivalence in common...
0
1414
by: Steven T. Hatton | last post by:
I suspect the core language is not the level at which introspection should be implemented in C++. That has been the choice of C#, and Java. Both of these languages made some trade-offs to accomplish this. Like threading, introspection can probably be implemented by third party providers. I tend to favor open standards that are acceptted and respected by a significant portion of the developers working in the field. Stroustrup states the...
4
1838
by: Steven T. Hatton | last post by:
Has there been any substantial progress toward supporting introspection/reflection in C++? I don't intend to mean it should be part of the Standard. It would, nonetheless, be nice to have a generally accepted means of providing introspection. My inclination is to have two general categories of introspection: dynamic introspection, and static intospection. In situations where it makes sense to use virtual functions and their...
6
2366
by: robert | last post by:
I get python crashes and (in better cases) strange Python exceptions when (in most cases) importing and using cookielib lazy on demand in a thread. It is mainly with cookielib, but remember the problem also with other imports (e.g. urllib2 etc.). And again very often in all these cases where I get weired Python exceptions, the problem is around re-functions - usually during re.compile calls during import (see some of the exceptions below). But...
6
3572
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows uncaught exception. How to catch an exception that happened before main() try { ... } catch (...) { ... } block? Is there a way?
14
4211
by: Dave Rahardja | last post by:
Is there a way to generate a series of statements based on the data members of a structure at compile time? I have a function that reverses the endianness of any data structure: /// Reverse the endianness of a data structure "in place". template <typename T> void reverseEndian(T&); Using boost, it is possible to provide the default implementation for all POD
0
686
by: Gabriel Genellina | last post by:
En Mon, 19 May 2008 07:52:25 -0300, Rustom Mody <rustompmody@gmail.comescribió: Use The Source, Luke! See pickle.py and pickletools.py - you may post here any questions you have then. -- Gabriel Genellina
0
9605
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,...
0
10392
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10136
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9208
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
7671
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
6893
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
5555
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...
0
5693
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4341
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 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.