473,395 Members | 1,497 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,395 software developers and data experts.

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 1753
"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.org> 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.invalid> wrote in message
news:7x************@ruckus.brouhaha.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.KeyError
type(x) = <type 'instance'>
dir(x) = ['__doc__', '__getitem__', '__init__', '__module__', '__str__',
'args']

type_ = exceptions.KeyError
value_ = 'foo'
traceback_ = <traceback object at 0x402e2e14>
traceback_.tb_frame = <frame object at 0x8177b3c>
traceback_.tb_lasti = 18
traceback_.tb_lineno = 6
traceback_.tb_next = None
dir(frame) = ['__class__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code',
'f_exc_traceback', '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*****@pythonware.com> wrote in message
news:ma**************************************@pyth on.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(traceback_, key).
traceback_.tb_frame = <frame object at 0x8177b3c>
traceback_.tb_lasti = 18
traceback_.tb_lineno = 6
traceback_.tb_next = 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
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...
24
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...
10
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...
0
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...
4
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...
6
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...
6
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...
14
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...
0
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. --...
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: 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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
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...

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.