1

我正在尝试捕获所有异常错误,然后在脚本结束时让它引发/显示所有回溯......

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

    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') + "\n")
        errors.write(traceback.format_exc() + '\n\n')

    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') + "\n")
        errors.write(traceback.format_exc() + '\n\n')

    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 <module>
#     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.

我将如何实现这一点,这有点难以解释,所以如果有些事情没有意义,请询问。

4

1 回答 1

3

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

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:\n\n{}".format(msg)

if reasons:
    raise ChainedException('\n'.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("\n".join(reasons))

输出:

Traceback (most recent call last):
  File "ok.py", line 17, in <module>
    raise ChainedException("\n".join(reasons))
__main__.ChainedException: The following exceptions occurred:

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 0

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 1

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 2

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 3

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    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]

请注意,这只适用于 Python 2.x。如果您使用的是 Python 3.x,则需要使用以下命令:

if reason:
    raise reason[1].with_traceback(reason[2])
于 2014-08-18T00:43:34.937 回答