This is how I do it:

>>> import traceback
>>> try:
...   int('k')
... except:
...   var = traceback.format_exc()
... 
>>> print(var)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'

You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...

Answer from mac on Stack Overflow
🌐
Tutorialspoint
tutorialspoint.com › python › python_sys_exc_info_method.htm
Python sys.exc_info() method
The Python sys.exc_info() method that returns a tuple containing information about the most recent exception caught by an except clause. The tuple consists of three elements, they are the exception type, the exception value and a traceback object.
🌐
Python
docs.python.org › 3 › library › sys.html
sys — System-specific parameters and functions
This function returns the old-style representation of the handled exception. If an exception e is currently handled (so exception() would return e), exc_info() returns the tuple (type(e), e, e.__traceback__).
🌐
Read the Docs
python.readthedocs.io › en › latest › c-api › exceptions.html
Exception Handling — Python 3.14.7 documentation
August 8, 2021 - Retrieve the old-style representation of the exception info, as known from sys.exc_info(). This refers to an exception that was already caught, not to an exception that was freshly raised.
🌐
Python Module of the Week
pymotw.com › 2 › sys › exceptions.html
Exception Handling - Python Module of the Week
There are times when an explicit ... a common handler function, but avoid passing the exception object to it explicitly. You can get the current exception for a thread by calling exc_info()....
🌐
Andrea Minini
andreaminini.net › computer-science › python › sysexc_info-function-in-python
Sys.exc_info() Function in Python - Andrea Minini
The exc_info() function returns information about the most recent exception that was raised. It is particularly useful for handling unexpected errors within a try except block. Note: Since this is a function from an external library (sys), to use it in a Python script, you need to import the ...
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
Format the exception part of a traceback using an exception value such as given by sys.last_exc. The return value is a list of strings, each ending in a newline. The list contains the exception’s message, which is normally a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred.
🌐
PyTutorial
pytutorial.com › python-sysexc_info-handling-exceptions-with-detailed-information
PyTutorial | Python sys.exc_info(): Handling Exceptions with Detailed Information
November 4, 2024 - Explore Python's sys.exc_info() for accessing detailed exception info, enabling effective error handling and debugging in complex applications.
🌐
Linuxtopia
linuxtopia.org › online_books › programming_books › python_programming › python_ch17s06.html
Python - Exception Functions
The sys module provides one function that provides the details of the exception that was raised. Programs with exception handling will occasionally use this function · The sys.exc_info function returns a 3-tuple with the exception, the exception's parameter, and a traceback object that pinpoints ...
Find elsewhere
🌐
Medium
saurabhk30.medium.com › python-try-except-tracing-73eb60745670
Python: Try Except Tracing. catch exception like a pro using… | by Saurabhk | Medium
September 20, 2023 - In addition to catching and handling ... using sys.exc_info(). This function returns a tuple containing the type of exception, the exception object and the traceback of the exception....
🌐
Loggly
loggly.com › home › blog › exceptional logging of exceptions in python
Exceptional Logging of Exceptions in Python - Loggly
October 25, 2022 - Setting exc_info to True will cause the logging to include the full stack trace…. exactly like logger.exception() does.
🌐
Fedorkobak
fedorkobak.github.io › python › standard_library › logging › exception_information.html
Exceptions information — Python
log_filename = "exception_information_files/excep_in_excep.log" logging.basicConfig( level=logging.INFO, filename=log_filename, filemode="w", format="%(asctime)s %(levelname)s %(message)s" ) def inside_exception(): try: 7/0 except: pass def outside_exception(): try: inside_exception() "hello" + 7 except: logging.error("Any error", exc_info=True) outside_exception() with open(log_filename) as f: print(f.read())
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › sys.exc_info.html
sys.exc_info() — Python Standard Library
sys.exc_info() -> (type, value, traceback)¶ · Return information about the most recent exception caught by an except clause in the current stack frame or in an older stack frame.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Explanation: except block catches the exception and retrieves detailed exception information using sys.exc_info(), which returns a tuple containing the exception type, value and traceback object.
🌐
Delft Stack
delftstack.com › home › api › python › python sys exc_info method
Python sys.exc_info() Method | Delft Stack
September 5, 2022 - The sys.exc_info() is an in-built Python function used to find information about an exception.
🌐
O'Reilly
oreilly.com › library › view › python-in-a › 0596001886 › re103.html
exc_info - Python in a Nutshell [Book]
March 3, 2003 - Nameexc_info Synopsisexc_info( )If the current thread is handling an exception, exc_info returns a tuple whose three items are the class, object, and traceback for the exception. If... - Selection from Python in a Nutshell [Book]
Author: Alex Martelli
Published: 2003
Pages: 656
🌐
UTK
web.eecs.utk.edu › ~bvanderz › cs365 › notes › Python › PythonExceptionHandling.html
exception handling
This code is non-protected code (i.e., code we do not expect to cause an exception) finally: code executed regardless of whether an exception occurs, and regardless of whether an exception is handled if one occurs Here is an example from the Python tutorial: import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as e: print ("I/O error({0}): {1}".format(e.errno, e.strerror)) except ValueError: print ("Could not convert data to an integer.") except: print ("Unexpected error:", sys.exc_info()[0]) raise The try mechanism operates as follows:
🌐
Cosmicpercolator
cosmicpercolator.com › 2016 › 01 › 13 › exception-leaks-in-python-2-and-3
Exception leaks in Python 2 and 3 | Kristján's Cosmic Percolator
January 13, 2016 - As long as sys.exc_info() was empty when the function was called, i.e. it was not called as part of exception handling, then the inner exception state is clear outside the Except clause.