2016-07-26 103 views
-2

我寫了一個嘗試,除了塊,我現在認識到是一個壞主意,因爲它不斷拋出難以調試的'盲'異常。問題是,我不知道如何去寫另一種方式,除了通過每個被調用的方法並手動讀取所有異常併爲每個方法創建一個案例。我怎樣才能解決這個嘗試除了塊?

你會如何構造這段代碼?

def get_wiktionary_audio(self): 
    '''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL''' 
    #this path is where the audio will be saved, only added the kwarg for testing with a different path 
    path="study_audio/%s/words" % (self.word.language.name) 
    try: 

     wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name) 
     wiktionary_page = urllib2.urlopen(wiktionary_url) 
     wiktionary_page = fromstring(wiktionary_page.read()) 
     file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0] 
     file_number = len(self.search_existing_audio()) 
     relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number) 
     full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path) 
     os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL)) 

    except: 
     return False 

    WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url) 
    return True 
+3

*「手動讀取所有異常併爲每個異常做出判斷」* ...這就是您需要執行的操作。盲目捕捉異常並不是一個好主意。 – solarissmoke

+2

@solarissmoke ...只捕獲你可以處理的異常。並非每個例外。有些需要通過..或者,除了塊將比try塊更長。使用異常來添加更多的代碼是Python編碼風格。 – Merlin

+1

這裏的信息太少了。問題是,你想在什麼情況下返回False?代碼不好的原因是它會聚集太多東西,並返回False來解決所有可能的錯誤。要決定如何更好地編寫代碼,您需要更詳細地考慮代碼中可能發生的情況以及您想要做什麼。 – BrenBarn

回答

0

通常情況下,異常會附帶可用於查明問題的錯誤字符串。你可以像這樣訪問該值:

try: 
    # code block 
except Exception as e: 
    print str(e) 

您還可以打印任何錯誤消息一起是什麼級別的異常使用repr方法:

try: 
    # code block 
except Exception as e: 
    print repr(e) 
+0

您還可以導入回溯,然後在except塊中調用traceback.print_exc()以打印異常信息和堆棧跟蹤 –

-1

首先你的代碼是聯合國Python化。您正在使用'self'作爲功能。 「self"通常保留給一個類,所以在閱讀你的代碼時,感覺不自然;其次,我的風格是排列"="符號以提高可讀性,我的建議是重新開始 - 使用標準的pythonic約定。經歷蟒蛇教程。

拋出異常的早期,往往-only代碼停止運行時,你也可以將一些命名的try/except外塊。

def get_wiktionary_audio(self): 
    '''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL''' 
    #this path is where the audio will be saved, only added the kwarg for testing with a different path 
    path    = "study_audio/%s/words" % (self.word.language.name) 
    try: 

     wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name) 
     wiktionary_page = urllib2.urlopen(wiktionary_url) 
     wiktionary_page = fromstring(wiktionary_page.read()) 
     file_URL  = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0] 
     file_number  = len(self.search_existing_audio()) 
     relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number) 
     full_path  = '%s/%s' % (settings.MEDIA_ROOT, relative_path) 
     os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL)) 

    except Exception as e : print e 


    WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url) 
    return True 
+1

'self'是函數的參數,這可能是一種方法。 – BrenBarn

+0

在上面的代碼中,「自我」是一種方法嗎? – Merlin

+1

我在說'get_wiktionary_audio'可能是一種方法。 (提問者可能只是省略了封閉類,因爲它與try/except塊的問題沒有密切關係。) – BrenBarn

0

的一種方式,我喜歡去它配置Python日誌記錄並記錄輸出結果,這爲您在日誌輸出方面提供了很大的靈活性,下面的例子記錄了異常回溯:

import traceback 
import logging 

logger = logging.getLogger(__name__) 

try: 
    ... 
except Exception as e: 
    logger.exception(traceback.format_exc()) # the traceback 
    logger.exception(e) # just the exception message 
相關問題