通常情況下,如果我進口socket
,我將能夠輕鬆地捕捉異常:如何捕獲我尚未完全導入的模塊的異常?
>>> import socket
>>> try:
... socket.gethostbyname('hello')
... except socket.gaierror:
... print('oops')
...
oops
但如果我只需要導入socket.gethostbyname
,它不會工作:
>>> 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
我也得到一個NameError
如果我試圖抓住gaierror
。
有沒有解決方法?用字符串捕捉異常是不可能的(例如,except 'socket.gaierror':
)?