Python 我怎样才能绕过这个街区?
我写了一个try-except块,我现在意识到这是个坏主意,因为它不断抛出难以调试的“盲”异常。问题是我不知道如何以另一种方式编写它,除了遍历调用的每个方法,手动读取所有异常并为每个异常创建案例之外 您将如何构造此代码Python 我怎样才能绕过这个街区?,python,django,Python,Django,我写了一个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 specif
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
通常,异常会附带错误字符串,可用于查明问题。您可以这样访问此值:
try:
# code block
except Exception as e:
print str(e)
您还可以使用repr方法打印异常类别以及任何错误消息:
首先,您的代码是非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
我喜欢使用的一种方法是配置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
手动读取所有异常并为每个异常创建案例。。。这就是你需要做的。盲目捕获异常从来不是一个好主意。@solarissmoke…只捕获您可以处理的异常。并非所有例外。有些需要被忽略。。或者,except块将比try块长。使用例外添加更多的代码是python编码风格。这里的信息太少。问题是,在什么情况下您希望返回False?代码不好的原因是它把太多的东西放在一起,并且对于所有可能的错误都返回False。要决定如何更好地编写它,您需要更详细地考虑代码中可能发生的情况以及您想要对其执行的操作。您还可以导入traceback,然后在except块中调用traceback.print_exc以打印异常信息和堆栈traceself是函数的一个参数,这很可能是一种方法。我是说get_wiktionary_audio可能是一种方法。提问者可能只是省略了封闭类,因为它与关于try/except块的问题无关。我不能假设Python的知识水平。可以在类外剪切和粘贴代码。get_wiktionary_audio确实是一个类方法,它与此方法在同一个类中。我应该声明,但我认为可以忽略它
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