如何打印回溯堆栈的第一行

How to print the first line from a traceback stack

假设我得到以下回溯:

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.

我已经设法提取错误详细信息,但让我感到困惑的是我将如何提取该行:

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

我正在查看 trace back 包中的方法,但想知道这里是否有人对此有经验

函数 traceback.format_exc 主要为此构建

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', '']

所以现在你想要第一行然后你可以简单地使用

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

瞧!你有你想要的

ALERT - Valid for Python 2.4.1 and above