python 异常回溯_关于python:在循环中捕获异常回溯,然后在脚本末尾引发错误...
我正在嘗試捕獲所有異常錯誤,然后在腳本結尾處使其引發/顯示所有回溯...
我有一個主腳本,例如調用我的下標:
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對象(請參見參考手冊),該對象在最初發生異常的位置封裝了調用堆棧。
總結
以上是生活随笔為你收集整理的python 异常回溯_关于python:在循环中捕获异常回溯,然后在脚本末尾引发错误...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: berkeley db java edi
- 下一篇: uniapp 输入框防抖节流_拉动一下控