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
import sys try: 1 / 0 except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() print(f"Exception type: {exc_type}") print(f"Exception value: {exc_value}") print(f"Traceback object: {exc_traceback}") Exception type: <class 'ZeroDivisionError'> Exception value: division by zero Traceback object: <traceback object at 0x0000016DCBD35000> This example uses sys.exc_info() method to retrieve the exception details and then uses the traceback module to print the traceback details โˆ’
๐ŸŒ
Python Programming
pythonprogramming.net โ€บ headless-error-handling-intermediate-python-tutorial
Headless Error Handling Python Tutorial
import sys try: a+b except: print(sys.exc_info()[0]) print(sys.exc_info()[1]) print(sys.exc_info()[2].tb_lineno) print('Error: {}. {}, line: {}'.format(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno))
๐ŸŒ
PyTutorial
pytutorial.com โ€บ python-sysexc_info-handling-exceptions-with-detailed-information
PyTutorial | Python sys.exc_info(): Handling Exceptions with Detailed Information
November 4, 2024 - For more on managing Python errors, ... and Python sys.stderr: Handling Error Output for handling program exits and error output respectively. sys.exc_info() is useful for nested try-except blocks where multiple exceptions might be raised and handled differently. Hereโ€™s an example...
๐ŸŒ
Fedorkobak
fedorkobak.github.io โ€บ python โ€บ standard_library โ€บ logging โ€บ exception_information.html
Exceptions information โ€” Python
log_filename = "exception_information_files/basic.log" fun_lines = [ lambda: "no_bug", # no_bug function lambda: 7/0, # ZeroDivisionError lambda: "hello" + 5784 # TypeError ] basic_logger = logging.getLogger("basic loger") basic_logger.level = logging.INFO handler = logging.FileHandler(log_filename, mode='w') handler.setFormatter( logging.Formatter('%(asctime)s|%(levelname)s|%(message)s') ) basic_logger.addHandler(handler) for fun in fun_lines: try: fun() except: basic_logger.error("===Any error===", exc_info=True) with open(log_filename) as file: print(file.read()) os.remove(log_filename)
๐ŸŒ
Iditect
iditect.com โ€บ guide โ€บ python โ€บ exception-sys-exc-info.html
Python sys.exc_info() method: get exception information
Here's a tutorial on using sys.exc_info() in Python: ... def divide(a, b): return a / b try: result = divide(10, 0) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() print(f"An error occurred: {exc_type}: {exc_value}") In this example, we use sys.exc_info() to get ...
๐ŸŒ
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 ...
Find elsewhere
๐ŸŒ
Programtalk
programtalk.com โ€บ python-examples-amp โ€บ sys.exc_info
sys.exc_info Example
June 10, 2016 - This works even if # there are none, because the split will return # [method] f = self.server.objmap[ns] # Look for the authorization method if self.server.config.authMethod != None: authmethod = self.server.config.authMethod if hasattr(f, authmethod): a = getattr(f, authmethod) # then continue looking for the method l = method.split(".") for i in l: f = getattr(f, i) except: info = sys.exc_info() try: resp = buildSOAP(faultType("%s:Client" % NS.ENV_T, "Method Not Found", "%s : %s %s %s" % (nsmethod, info[0], info[1], info[2])), encoding = self.server.encoding, config = self.server.config) fin
๐ŸŒ
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
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ sys โ€บ exceptions.html
Exception Handling - Python Module of the Week
This example avoids introducing a circular reference between the traceback object and a local variable in the current frame by ignoring that part of the return value from exc_info(). If the traceback is needed (e.g., so it can be logged), explicitly delete the local variable (using del) to avoid cycles. $ python sys_exc_info.py Handling RuntimeError exception with message "This is the error message" in Thread-2 Handling RuntimeError exception with message "This is the error message" in Thread-1
๐ŸŒ
IT trip
en.ittrip.xyz โ€บ python
Mastering Exception Handling in Python with sys.exc_info(): A Detailed Guide | IT trip
November 5, 2023 - The code snippet above will catch any exception, retrieve its details, and print them out. Itโ€™s a basic example of how to implement `sys.exc_info()` in a Python program.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ logging.html
logging โ€” Logging facility for Python
While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized Formatters would be used with particular Handlers. If no handler is attached to this logger (or any of its ancestors, taking into account the relevant Logger.propagate attributes), the message will be sent to the handler set on lastResort. Changed in version 3.2: The stack_info parameter was added. Changed in version 3.5: The exc_info parameter can now accept exception instances.
๐ŸŒ
Orsinium
pythonetc.orsinium.dev โ€บ posts โ€บ exc-info
Python etc / logging exc_info
from logging import getLogger logger = getLogger(__name__) channels = {} def update_channel(slug, name): try: old_name = channels[slug] except KeyError as exc: logger.error(repr(exc)) ... update_channel('pythonetc', 'Python etc') # Logged: KeyError('pythonetc') This example has a few issues: There is no explicit log message. So, when it fails, you can't search in the project where this log record comes from. There is no traceback. When the try block execution is more complicated, we want to be able to track where exactly in the call stack the exception occurred. To achieve it, logger methods provide exc_info argument.
๐ŸŒ
docs.python.org
docs.python.org โ€บ 3 โ€บ library โ€บ sys.html
sys โ€” System-specific parameters and functions
Raise an auditing event and trigger ... more information about the event. The number and types of arguments for a given event are considered a public and stable API and should not be modified between releases. For example, one auditing event is named os.chdir. This event has one argument called path that will contain the requested new working directory. sys.audit() will call the existing auditing hooks, passing the event name and arguments, and will re-raise the first exception from any ...
๐ŸŒ
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 ...
๐ŸŒ
Beautiful Soup
tedboy.github.io โ€บ python_stdlib โ€บ generated โ€บ generated โ€บ sys.exc_info.html
sys.exc_info() โ€” Python Standard Library
Return information about the most recent exception caught by an except clause in the current stack frame or in an older stack frame.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ traceback
traceback โ€“ Extract, format, and print exceptions and stack traces. - Python Module of the Week
import traceback import sys from traceback_example import produce_exception try: produce_exception() except Exception, err: print 'print_exception():' exc_type, exc_value, exc_tb = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_tb) $ python traceback_print_exception.py Traceback (most recent call last): File "traceback_print_exception.py", line 16, in <module> produce_exception() File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exception raise RuntimeError() RuntimeError print_exception():
๐ŸŒ
Loggly
loggly.com โ€บ home โ€บ blog โ€บ exceptional logging of exceptions in python
Exceptional Logging of Exceptions in Python - Loggly
October 25, 2022 - When you say raise NoMatchingRestaurants(criteria) from err, that raises an exception of typeNoMatchingRestaurants. This raised exception has an attribute named __cause__, whose value is the instigating exception.