Search code examples
pythonexceptionstack-tracetraceback

How to print the first line from a traceback stack


Suppose I am given the following traceback:

Traceback (most recent call last):    
  File "<wingdb_compile>", line 3, in <module>    
  File "C:\Python34\lib\ftplib.py", line 419, in login    
    resp = self.sendcmd('PASS ' + passwd)    
  File "C:\Python34\lib\ftplib.py", line 272, in sendcmd    
    return self.getresp()    
  File "C:\Python34\lib\ftplib.py", line 245, in getresp    
    raise error_perm(resp)    
ftplib.error_perm: 530 Login incorrect.

I have managed to extract the Error details but what has stumped me is how would I extract the line:

File "<wingdb_compile>", line 3, in <module>

I was looking at methods in the trace back package but wondered if any one had experience with that here


Solution

  • The function traceback.format_exc is built primarily for this

    This is like print_exc(limit) but returns a string instead of printing to a file.

    >>> import traceback
    >>> try:
    ...     x = 2/0
    ... except:
    ...     error = traceback.format_exc()
    ... 
    >>> error
    'Traceback (most recent call last):\n  File "<stdin>", line 2, in <module>\nZeroDivisionError: division by zero\n'
    >>> linesoferror = error.split('\n')
    >>> linesoferror
    ['Traceback (most recent call last):', '  File "<stdin>", line 2, in <module>', 'ZeroDivisionError: division by zero', '']
    

    So now you wanted the first line then you can simply use

    >>> linesoferror[1]
    '  File "<stdin>", line 2, in <module>'
    

    Voila! You have what you want

    ALERT - Valid for Python 2.4.1 and above