从traceb隐藏文件

2024-09-30 14:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个尝试/除非

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

比如说,我得到一个错误:

^{pr2}$

有没有方法可以这样显示或自定义它:

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')

没有显示文件路径?在


Tags: inpyselfreturnresponselinefileraise
2条回答

虽然不能调整Python解释器的输出,但是可以使用traceback module来模拟它。在

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

^{}函数将为您提供一个多行字符串,您可以根据需要修改和打印该字符串。在

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)

不是那么简单,但是您可以使用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):

我试过了:

^{pr2}$

打印:

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

相关问题 更多 >