【在python中异常的分析】教程文章相关的互联网学习教程文章

如果没有转换说明符,Python不会在%上引发异常【代码】

用于字符串格式化的%运算符描述为here. 通常,当呈现没有转换说明符的字符串时,它将引发TypeError:并非在字符串格式化期间转换所有参数.例如,“”%1将失败.到现在为止还挺好. 但是,有时它不会失败,如果%运算符右边的参数是空的:“”%[]或“”%{}或“”%()将静默返回空字符串,并且看起来很公平. 与“%s”相同而不是空字符串会将空对象转换为字符串,除了最后一个会失败,但我认为这是%运算符问题的一个实例,它由format方法解...

python爬虫 requests异常:requests.exceptions.ConnectionError: HTTPSConnectionPool Max retries exceeded

使用 requests抓取网页时会碰到如下异常:requests.exceptions.ConnectionError: HTTPSConnectionPool Max retries exceeded原因1.http的连接数超过最大限制,默认的情况下连接是Keep-alive的,所以这就导致了服务器保持了太多连接而不能再新建连接。 2.ip被封 3.请求过快解决1.在header中不使用持久连接‘Connection’: ‘close’或requests.adapters.DEFAULT_RETRIES = 5 2.若是请求过快,可设置time.sleep 3.使用代理ip 4.Reque...

python – “pip install Django”给出了异常【代码】

我试图在命令提示符下使用“pip install django”在Windows 10上安装django,它给了我这个例外.我在这做错了什么?C:\Users\Amit>pip install django Collecting djangoUsing cached Django-1.9.2-py2.py3-none-any.whl Installing collected packages: django Exception: Traceback (most recent call last):File "c:\program files (x86)\python35-32\lib\site-packages\pip\basecommand.py", line 209, in mainstatus = self.run...

python – pytest异常无类型对象不可调用【代码】

在test1.py我有下面的代码@pytest.fixture(scope="session") def moduleSetup(request):module_setup = Module_Setup()request.addfinalizer(module_setup.teardown())return module_setupdef test_1(moduleSetup):print moduleSetupprint '...'#assert 0# def test_2(moduleSetup): # print moduleSetup # print '...' # #assert 0在conftest.py我有class Module_Setup:def __init__(self):self.driver = webdriver.F...

在Python中使用内置str()类型的潜在异常【代码】

在Python中使用内置类型(如int和float)时,通常在输入可能不可靠的情况下使用异常处理:def friendly_int_convert(val):"Convert value to int or return 37 & print an alert if conversion fails"try:return int(val)except ValueError:print('Sorry, that value doesn\'t work... I chose 37 for you!')return 37使用str()时是否有任何突出的边缘情况需要注意?def friendly_str_convert(val):"Convert value to str or return '...

如何从python CGI脚本中引发http错误/异常?【代码】

如何从python CGI脚本中引发http错误/异常? 是否有必要打印适当的标题:print '''Status: 501 Not Implemented Content-type: text/html'''这似乎不正常. 我有一个非常基本的设置,即IIS7路由* .py CGI脚本到python25.exe执行.我没有使用任何WSGI或FastCGI.使用“普通”CGI模块:cgitb和cgi解决方法:这似乎就是这样做的方式.只要您正确遵循标题格式. 这是其他人或多或少地提出同样问题的人. Returning http status codes in Python...

python – SWIG包装C库最优雅的方式来引发异常【代码】

我最近转换了一个库,我最初使用Boost Python包装在C中编写,使用SWIG包装来支持更多语言.我从C切换到C,因为该库只包含一组函数,我也希望该库可以从C调用(无需用C编译器编译整个程序).然而,有一件事不容易移植,一小部分功能需要能够报告错误.在C / Boost Python中,使用throw和异常翻译非常优雅. 如果有一部分函数报告错误,最优雅的方式(在C语言和包装语言方面)会是什么?解决方法:我就是这样做的. %{…%}块将其内容插入到包装文件中...

python – 扭曲的Unicode异常【代码】

在我的生产服务器上,我定期发生unicode错误但不在我的桌面上.它出现在日志中:2011-03-17 13:14:53+0000 [GameProtocol,941,95.78.43.17] <unicode instance at 0x9e304a0 with str error:Traceback (most recent call last):File "/usr/local/lib/python2.6/dist-packages/twisted/python/reflect.py", line 546, in _safeFormatreturn formatter(o)UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-26...

python – 在单元测试中,如何确定传递给自定义异常的参数?【代码】

class AppError(Exception): passclass MissingInputError(AppError):em = {1101: "Date input is missing. Please verify.", 1102: "Key input is missing. Please verify.", 1103: "Stn input is missing. Please verify."}# and so on ...…def validate(self):""" Method of Input class to validate input and save it """params = self.__paramsif 'dt' in params:self.__validateKey(escape(params['dt...

Python兼容性:捕获异常【代码】

我有一个应用程序,需要在所有“现代”Python版本中工作,这意味着2.5-3.2.我不想要两个代码库,所以2to3不是一个选项. 考虑这样的事情:def func(input):if input != 'xyz':raise MyException(some_function(input))return some_other_function(input)如何捕获此异常,以获取对异常对象的访问权限?除了MyException之外,e:在Python 3中无效,除了MyException,因为e:在python 2.5中无效. 显然,它本可以返回异常对象,但我希望,我不必这...

确保在Python中捕获所有异常【代码】

我已经用Python编程了一段时间,但我的努力主要是创??建小实用程序脚本.我认为Python是一种很棒的语言,因为它很有趣,它可以很容易地编写干净的代码. 然而,有一个烦恼我还没有找到治愈方法:由于它的动态特性,可以从各种来源抛出异常,如果它们没有被捕获它们会杀死你的程序.对我来说,这对“大”计划来说是一种痛苦. 在Java中(不是我比我更熟悉Java),编译器实际上静态地强制执行异常处理,以便捕获所有可能的异常.是否有可能用Python实...

python3 异常处理【代码】

try:dic = {a: 1,}dic[b] # KeyErrorlst = [a, b]lst[10] # IndexErrors = "2GB"s = int(s) # ValueErrorexcept ValueError as e: # e为异常的值print(e) except KeyError as e:print(e) except IndexError as e:print(e) except Exception as e: # 万能异常print(e) else:print("没有异常会执行我.") # 一般用来关闭文件等操作 finally:print("有没有异常都会执行我")# 异常包括三部分: 追踪信息/异常类型/异常的值 # try: ...

总是在异常时总是调用python调试器的一般方法【代码】

我希望我的调试器在遇到异常时运行post_mortem(),而不必修改我正在处理的源.我看到很多例子涉及在try / except块中包装代码,但我想让它始终运行,无论我在做什么. 我研究了一个python包装器脚本,但是它变得丑陋且几乎无法使用. 我使用的是pudb,它与pdb的API等价,所以pdb特定的答案很好.我在我的编辑器(vim)中运行代码,并希望在遇到异常时让pm出现.解决方法:花了几个月的时间没有做任何事情,但我偶然发现了一个解决方案.我相信对于经...

python – Scrapy异常 – exceptions.AttributeError:’unicode’对象没有属性’select’【代码】

我写了一只蜘蛛,但每当我运行这个蜘蛛时我都会收到这个错误:Traceback (most recent call last):File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 824, in runUntilCurrentcall.func(*call.args, **call.kw)File "/usr/local/lib/python2.7/dist-packages/twisted/internet/task.py", line 607, in _ticktaskObj._oneWorkUnit()File "/usr/local/lib/python2.7/dist-packages/twisted/internet/tas...

python – RESTful API中未处理的异常没有得到jsonify’ed【代码】

我有以下代码 – 它有一个http处理函数(func1)和一个RESTful API(func2),它们可以通过URL / test1和/ test2访问.我有一个异常处理函数(exception_handler),它由app.errorhandler()修饰,以确保所有未处理的异常都是jsonify’ed并作为响应发回.from flask import Flask, jsonify from flask.ext.restful import Resource, Apiapp = Flask(__name__) api = Api(app)@app.errorhandler(Exception) def exception_handler(e):return jso...