Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For python is there a way to print variables scope from context where exception happens?

Is there a way to print variables scope from context where exception happens?

For example:

def f():
    a = 1
    b = 2
    1/0

try:
    f()
except:
    pass # here I want to print something like "{'a': 1, 'b': 2}"
like image 649
Soid Avatar asked Mar 16 '11 15:03

Soid


People also ask

How do you print exception in Python?

If you are going to print the exception, it is better to use print(repr(e)) ; the base Exception. __str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.

How do you catch and print exceptions in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

How does Python handle specific exceptions?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

How do I identify exceptions in Python?

To get exception information from a bare exception handler, you use the exc_info() function from the sys module. The sys. exc_info() function returns a tuple that consists of three values: type is the type of the exception occurred.


1 Answers

You can use the function sys.exc_info() to get the last exception that occurred in the current thread in you except clause. This will be a tuple of exception type, exception instance and traceback. The traceback is a linked list of frame. This is what is used to print the backtrace by the interpreter. It does contains the local dictionnary.

So you can do:

import sys

def f():
    a = 1
    b = 2
    1/0

try:
    f()
except:
    exc_type, exc_value, tb = sys.exc_info()
    if tb is not None:
        prev = tb
        curr = tb.tb_next
        while curr is not None:
            prev = curr
            curr = curr.tb_next
        print prev.tb_frame.f_locals
like image 182
Sylvain Defresne Avatar answered Oct 02 '22 03:10

Sylvain Defresne