python 异常回溯_关于python:在循环中捕获异常回溯,然后在脚本末尾引发错误...

本文档展示了如何在Python脚本中捕获和记录多个异常回溯。通过使用traceback模块,可以在异常发生时保存回溯信息,并在循环结束后统一打印或处理这些错误。此外,还提出了自定义异常类`ChainedException`来组合多个异常信息。这种方法有助于在主脚本中集中处理错误,并确保所有错误信息都能被适当地记录和处理。
摘要由CSDN通过智能技术生成

我正在尝试捕获所有异常错误,然后在脚本结尾处使其引发/显示所有回溯...

我有一个主脚本,例如调用我的下标:

errors = open('MISC/ERROR(S).txt', 'a')

try:

execfile("SUBSCRIPTS/Test1.py", {})

except Exception:

## Spread over two calls of errors.write for readability in code...

errors.write(strftime('%d/%m/%Y %H:%M:%S') +"

")

errors.write(traceback.format_exc() + '

')

try:

execfile("SUBSCRIPTS/Test2.py", {})

except Exception:

## Spread over two calls of errors.write for readability in code...

errors.write(strftime('%d/%m/%Y %H:%M:%S') +"

")

errors.write(traceback.format_exc() + '

')

errors.close()

此脚本使用追溯模块从脚本中检索错误...

在下一个示例中,这是我当前脚本的样子:

for x in y:

if"example" in x:

for tweet in tweetlist:

# Try

try:

twitter.update_status(status=tweet)

# Do some other stuff here if it suceeeds like...

print"oo example worked"

# Damn it failed, grab the whole traceback?

except Exception as reason:

FailedTweet = True

# Do some other stuff here like...

print"I did other stuff"

if FailedTweet:

print reason # Printing the reason because I don't know how to throw the exception error (full error)

基本上,存在一个大循环,可能会在此行中出现错误:twitter.update_status(status=tweet),如果确实如此,我希望它能够捕获回溯错误,因为它在一个循环中,然后在脚本完成时,它可能不止一个 我希望它将所有回溯错误发送回主脚本,以便将其全部写入错误文件。

从代码的第一位向文件写入错误的示例:

# 17/08/2014 12:30:00

# Traceback (most recent call last):

#   File"C:\Main.py", line 117, in execute_subscripts

#     execfile("SUBSCRIPTS/Test1.py", {})

#   File"SUBSCRIPTS/Test1.py", line 440, in

#     twitter.update_status(status=string)

#   File"C:\Python27\lib\site-packages\twython\endpoints.py", line 90, in update_status

#     return self.post('statuses/update', params=params)

#   File"C:\Python27\lib\site-packages\twython\api.py", line 234, in post

#     return self.request(endpoint, 'POST', params=params, version=version)

#   File"C:\Python27\lib\site-packages\twython\api.py", line 224, in request

#     content = self._request(url, method=method, params=params, api_call=url)

#   File"C:\Python27\lib\site-packages\twython\api.py", line 194, in _request

#     retry_after=response.headers.get('retry-after'))

# TwythonError: Twitter API returned a 403 (Forbidden), This request looks like it might be automated. To protect our users from spam and other malicious activity, we can't complete this action right now. Please try again later.

我将如何实现这一点,这很难解释,所以如果有什么不对的地方,请询问。

只需将回溯数据保存在列表中,然后在循环完成后打印列表的内容。

import traceback

reasons = []

for x in y:

if"example" in x:

for tweet in tweetlist:

# Try

try:

twitter.update_status(status=tweet)

# Do some other stuff here if it suceeeds like...

print"oo example worked"

# Damn it failed, grab the whole traceback?

except Exception:

reasons.append(traceback.format_exc())

# Do some other stuff here like...

print"I did other stuff"

for reason in reasons:

print reason

# If you want to raise a single exception that shows the traceback for

# each exception, you can do this:

class ChainedException(Exception):

def __init__(self, msg):

msg ="The following exceptions occurred:

{}".format(msg)

if reasons:

raise ChainedException('

'.join(reasons))

ChainedException的示例用法:

reasons = []

for i in range(5):

try:

raise Exception("Blah {}".format(i))

except Exception:

reasons.append(traceback.format_exc())

if reasons:

raise ChainedException("

".join(reasons))

输出:

Traceback (most recent call last):

File"ok.py", line 17, in

raise ChainedException("

".join(reasons))

__main__.ChainedException: The following exceptions occurred:

Traceback (most recent call last):

File"ok.py", line 12, in

raise Exception("Blah {}".format(i))

Exception: Blah 0

Traceback (most recent call last):

File"ok.py", line 12, in

raise Exception("Blah {}".format(i))

Exception: Blah 1

Traceback (most recent call last):

File"ok.py", line 12, in

raise Exception("Blah {}".format(i))

Exception: Blah 2

Traceback (most recent call last):

File"ok.py", line 12, in

raise Exception("Blah {}".format(i))

Exception: Blah 3

Traceback (most recent call last):

File"ok.py", line 12, in

raise Exception("Blah {}".format(i))

Exception: Blah 4

编辑:

如果您真的只在乎从整个例外列表中提出一个例外,则可以这样做:

import traceback

reason = None

for x in y:

if"example" in x:

for tweet in tweetlist:

# Try

try:

twitter.update_status(status=tweet)

# Do some other stuff here if it suceeeds like...

print"oo example worked"

# Damn it failed, grab the whole traceback?

except Exception:

reason = sys.exc_info() # We're not putting it in a list because you only care about one.

# Do some other stuff here like...

print"I did other stuff"

if reason:

raise reason[0], reason[1], reason[2]

请注意,这仅适用于Python2.x。 如果您使用的是Python 3.x,则需要使用以下代码:

if reason:

raise reason[1].with_traceback(reason[2])

嗯,很好的逻辑。然后如何创建异常,以便主脚本意识到存在错误/将错误记录到文件中?

您实际上想看到什么记录?只是一个或多个异常发生的通知,还是所有回溯?您只能对父脚本提出一个例外,那应该是什么?发生的实际异常之一,还是指示一个或多个状态更新失败的一般性异常?

@Ryflex Ive更新了我的答案,以显示我认为您正在寻找的东西。

恩,我只是再次浏览了twitter API;即错误代码,并且当代码通过for循环时,我不会收到不同的错误代码,因此在这种情况下,只抛出一个完整的完整回溯traceback.format_exc()效果会更好,如我的原始文章所示。 ;我只是不知道如何将回溯发送回主脚本...在将原因设置如下后,我会做raise reason吗?

香港专业教育学院搜索系统文档,但我找不到任何有关exc_info()的每个部分做什么...

@Ryflex如果没有在堆栈上的任何地方处理异常,则返回包含三个None值的元组。否则,返回的值为(类型,值,回溯)。它们的含义是:type获取正在处理的异常的异常类型(一个类对象); value获取异常参数(其关联值或要引发的第二个参数,如果异常类型是类对象,则始终为类实例); traceback获取一个traceback对象(请参见参考手册),该对象在最初发生异常的位置封装了调用堆栈。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值