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}"
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With