我有这段代码,
try:
print "what"
newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])
print newClassName
except:
print "HAHA"
这总是打印“HAHA”,尽管事实上我在控制台中运行newClassName = ...代码并且它有效。
为什么会这样?
修改
def newGetAllInformation(searchTerm):
nameAndNumberStore = modifySearchTerm(searchTerm)
urlStore = modifyUrl(nameAndNumberStore) # need to make the change here -- why not I go to the site, check for Course name - if that is not there switch, if it is then scrape
soup = getHtml(urlStore)
storeOfBooks = []
storeOfBooks = scrape(soup,nameAndNumberStore)
print nameAndNumberStore[0]
try:
newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])
nameAndNumberStore = modifySearchTerm(newClassName.departmentName + " " + nameAndNumberStore[1])
urlStore = modifyUrl(nameAndNumberStore)
soup = getHtml(urlStore)
storeOfBooks = scrape(soup,nameAndNumberStore)
except:
print "HAHA"
return storeOfBooks
修改 经过进一步的调查 - 也就是说,手动输入一个有效的代码(有效),我认为从阵列中获取代码有一些东西 - 尽管两者都是相同的数据类型(字符串)。
所以newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = "econ")
适用于文件,newClassName = CourseNameAndCodeAssocition.objects.get(departmentCode__iexact = nameAndNumberStore[0])
,其中nameAndNumberStore[0]
包含 econ
答案 0 :(得分:9)
请修改代码,运行它并告诉我们您获得的异常:
try:
print "what"
newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])
print newClassName
except Exception as e:
print "HAHA"
print e
此外,在您的盒子上安装调试器可能会有所帮助。我可以推荐Eclipse与PyDev结合使用,但这是个人选择。那里有很多很棒的选择。
答案 1 :(得分:2)
将其更改为:
except CourseNameAndCodeAssociation.DoesNotExist:
您创建的每个模型都会获得自己的DoesNotExist
异常,从而扩展核心ObjectDoesNotExist
异常。
同样最好的方法是仅在您希望失败的精确线周围使用try
... except
。写一个更加pythonic的方式来写你所拥有的东西:
department_code = name_and_number_store[0]
class_names = CourseNameAndCodeAssociation.objects.all()
try:
new_class_name = class_names.get(departmentCode__iexact=department_code)
except CourseNameAndCodeAssociation.DoesNotExist:
print "HAHA"
else:
search_term = u'%s %s' % (new_class_name.departmentName,
name_and_number_store[1])
name_and_number_store = modify_search_term(search_term)
url_store = modify_url(name_and_number_store)
soup = get_html(url_store)
store_of_books = scrape(soup, name_and_number_store)
请注意,Python中的约定是对变量,属性和函数名使用lowercase_underscored_names
,对类名使用CamelCaseNames
(实例名称是变量或属性)。