我怎么能绕过这个尝试除了块?

时间:2016-07-26 04:10:31

标签: python django

我写了一个尝试,除了块我现在意识到这是一个坏主意,因为它继续投掷盲目'难以调试的异常。问题是我不知道如何以另一种方式编写它,除了遍历每个被调用的方法并手动读取所有异常并为每个方法创建一个案例。

您将如何构建此代码?

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 个答案:

答案 0 :(得分:0)

通常,异常带有错误字符串,可用于查明问题。您可以像这样访问此值:

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

您还可以使用repr方法打印出任何类型的异常以及任何错误消息:

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

答案 1 :(得分: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

答案 2 :(得分:-1)

首先你的代码是非pythonic。您正在使用'self'作为函数。 " self"通常保留给一个班级。所以在阅读你的代码时,感觉不自然。其次,我的风格是排列"="符号以便于阅读。我的建议是重新开始 - 使用标准的pythonic约定。你可以通过python教程来获得这个。

在代码停止运行时,尽早并经常抛出异常。您还可以在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