[Python] How to print errors like python does by default?

Discussão em 'Python' iniciado por Stack, Outubro 25, 2024.

  1. Stack

    Stack Membro Participativo

    Considering the following errornous function:

    def inner():
    raise Exception("message")


    If I run the function I get an error like:

    Traceback (most recent call last):
    File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()
    ^^^^^^
    File "<input>", line 1, in <module>
    File "<input>", line 2, in inner
    Exception: message


    Now I wish for logging purposes to get this kind of error messaging into code, what I tried was using traceback.format_exc() as well as unpacking sys.exc_info()

    def outer():
    try:
    inner()
    except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    print(exc_type)
    print(exc_obj)
    print(exc_tb)
    print(traceback.format_tb(exc_tb))
    print(traceback.format_exc())


    which gives:

    >>> outer()
    <class 'Exception'>
    message
    <traceback object at 0x10affca00>
    [' File "<input>", line 3, in outer\n', ' File "<input>", line 2, in inner\n']
    Traceback (most recent call last):
    File "<input>", line 3, in outer
    File "<input>", line 2, in inner
    Exception: message


    While format_exc() correctly formats the latter part, it does not include the import "line" information

    /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()


    How would I get that information and log that?

    Continue reading...

Compartilhe esta Página