在python項目中,我使用連接到(mpd。)服務器的模塊python-mpd2。服務器在一分鐘後關閉連接。模塊提供的大多數方法將導致mpd.ConnectionError
。如何正確捕獲模塊引發的異常?
我嘗試構建一個包裝類,它試圖執行該方法,但在之前斷開連接的情況下重新連接到服務器。
什麼我是這樣的:
from mpd import MPDClient, MPDError
class MPDProxy:
def __init__(self, host="localhost", port=6600, timeout=10):
self.client = MPDClient()
self.host = host
self.port = port
self.client.timeout = timeout
self.connect(host, port)
def __getattr__(self, name):
return self._call_with_reconnect(getattr(self.client, name))
def connect(self, host, port):
self.client.connect(host, port)
self.client.consume(1) # when we call self.client.next() the previous stream is deleted from the playlist
if len(self.client.playlist()) > 1:
cur = (self.client.playlist()[0][6:])
self.client.clear()
self.add(cur)
def _call_with_reconnect(self, func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except ConnectionError:
self.connect(self.host, self.port)
return func(*args, **kwargs)
return wrapper
mpd_proxy = MPDProxy()
然而,ConnectionError
不會被抓到。
>>> from MPDProxy import mpd_proxy
>>> mpd_proxy.play()
>>> mpd_proxy.stop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./MPDProxy.py", line 26, in wrapper
func(*args, **kwargs)
File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 588, in decorator
return wrapper(self, name, args, bound_decorator(self, returnValue))
File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 229, in _execute
return retval()
File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 583, in decorator
return function(self, *args, **kwargs)
File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 352, in _fetch_nothing
line = self._read_line()
File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 260, in _read_line
raise ConnectionError("Connection lost while reading line")
mpd.ConnectionError: Connection lost while reading line
我該如何正確捕獲ConnectionError?
我沒有看到'在你的代碼decorator'任何地方。 – BrenBarn
你可以在此擴展嗎?我知道有提到裝飾器的錯誤消息,但我沒有在我的代碼中使用它。 – speendo