从回溯中隐藏文件

时间:2014-08-12 19:20:28

标签: python traceback

我有尝试/除

try:
    return dispatcher.dispatch(path, method, params)
except Exception as expt:
    webApp.logger.error(str(expt))
    raise ValueError('Imposible conectarse')

让我们说,例如,我收到了这个错误:

Traceback (most recent call last):
  File "/home/leandro/.virtualenvs/DesktopProxyV2/local/lib/python2.7/site-packages/eventlet/wsgi.py", line 389, in handle_one_response
    result = self.application(self.environ, start_response)
  File "/home/leandro/Desarrollo/desktop_proxy/modulos/proxy/webproxy.py", line 60, in request_handler
    raise ValueError('Imposible conectarse')
ValueError: Imposible conectarse

有没有办法像这样显示或自定义它:

Traceback (most recent call last):
  File "wsgi.py", line 389, in handle_one_response
    result = self.application(self.environ, start_response)
  File "webproxy.py", line 60, in request_handler
    raise ValueError('Imposible conectarse')

没有它显示文件路径?

2 个答案:

答案 0 :(得分:1)

虽然您无法调整Python解释器的输出,但您可以使用traceback module 模仿

您可以将整个应用程序包装在try..except语句中,并从那里打印出您自己的消息。

traceback.format_exec功能会为您提供一个多行字符串,然后您可以根据需要进行修改和打印。

def main():
    #Your application code

if __name__ == "__main__":
    try:
        main()
    except BaseException:
        lines = traceback.format_exc().splitlines()
        for line in lines:
            print re.sub(r'File ".*[\\/]([^\\/]+.py)"', r'File "\1"', line)

答案 1 :(得分:0)

不是那么简单,但您可以使用traceback模块过滤掉追溯。

try:
    # something which throws
except Exception as expt:
    import traceback
    trace_lines = traceback.format.exc().splitlines()
    # tracelines contains all the lines from the traceback
    # Accordingly filter for e.g. check for lines containing File and then extract only the filename from the complete path and print it

例如trace_lines[0]将为Traceback (most recent call last):

我试过了:

try:
    a = 1/0
except Exception as e:
    lines = traceback.format_exc().splitlines()
    print (lines)

打印:

['Traceback (most recent call last):', '  File "<stdin>", line 2, in <module>', 'ZeroDivisionError: integer division or modulo by zero']