Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

python - 如何在不停止程序的情况下打印完整的回溯?(How to print the full traceback without halting the program?)

I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. (我正在编写一个程序,该程序可以解析10个网站,找到数据文件,保存文件,然后解析它们以生成可以在NumPy库中轻松使用的数据。) There are tons of errors this file encounters through bad links, poorly formed XML, missing entries, and other things I've yet to categorize. (有过不良链接,不好的XML,缺项,其他的事情我还没有进行分类文件遭遇的错误。) I initially made this program to handle errors like this: (我最初制作该程序来处理以下错误:)

try:
    do_stuff()
except:
    pass

But now I want to log errors: (但是现在我想记录错误:)

try:
    do_stuff()
except Exception, err:
    print Exception, err

Note this is printing to a log file for later review. (请注意,这是打印到日志文件以供以后查看。) This usually prints very useless data. (这通常会打印非常无用的数据。) What I want is to print the exact same lines printed when the error triggers without the try-except intercepting the exception, but I don't want it to halt my program since it is nested in a series of for loops that I would like to see to completion. (我想要的是在错误触发时打印完全相同的行,而没有try-except拦截异常,但是我不希望它暂停我的程序,因为它嵌套在我想要的一系列for循环中看到完成。)

  ask by chriscauley translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

traceback.format_exc() or sys.exc_info() will yield more info if that's what you want. (如果那是您想要的, traceback.format_exc()sys.exc_info()将产生更多信息。)

import traceback
import sys

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
    # or
    print(sys.exc_info()[2])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...