如何为未完全导入的模块捕获异常? [英] How do I catch an exception for a module that I've not fully imported?
问题描述
通常,如果我导入了 socket
,我将能够轻松捕获异常:
>>>导入套接字
>>>尝试:
... socket.gethostbyname('hello')
... socket.gaierror除外:
... print('oops')
...
oops
但是如果我只是导入 socket.gethostbyname
,将无法正常工作:
>>从套接字导入gethostbyname
>>尝试:
... gethostbyname('hello')
... socket.gaierror:
... print('oops')
...
回溯(最近一次呼叫最近):
文件< stdin>,第3行,在< module>中。
NameError:未定义名称 socket
我也得到 NameError
如果我尝试捕获 gaierror
。
有没有解决方法?这个?
如果您不想导入完整的模块,则也可以直接导入异常。 PEP8声明您被允许这样做。
来自套接字导入gethostbyname,gaierror
http:// www .python.org / dev / peps / pep-0008 /#imports
Normally, if I imported socket
, I would be able to easily catch exceptions:
>>> import socket
>>> try:
... socket.gethostbyname('hello')
... except socket.gaierror:
... print('oops')
...
oops
But if I just import socket.gethostbyname
, it won't work:
>>> from socket import gethostbyname
>>> try:
... gethostbyname('hello')
... except socket.gaierror:
... print('oops')
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'socket' is not defined
I also get a NameError
if I try to catch gaierror
.
Is there any workaround for this? Is it not possible to catch an exception with a string (eg. except 'socket.gaierror':
)?
If you do not want to import the full module you can simply import the exception aswell. PEP8 states that you are allowed to do.
from socket import gethostbyname, gaierror
http://www.python.org/dev/peps/pep-0008/#imports
这篇关于如何为未完全导入的模块捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!