在contextmanager中使用yield两次

时间:2016-03-29 21:51:41

标签: python yield contextmanager mpd

我试图用contextmanager隐藏一些try / except复杂性。这是一个简单的例子:

from contextlib import contextmanager
import mpd

mpdclient = mpd.MPDClient()
mpdclient.connect("localhost", 6600)

@contextmanager
def mpdcontext():
  try:
    yield
  except mpd.ConnectionError:
    mpdclient.connect("localhost", 6600)

with mpdcontext():
  mpdclient.status()

with mpdcontext():
  mpdclient.lsinfo()

现在,正如我所理解的那样,在调用yield时执行with语句中的块。在我的情况下,如果这引发异常,我重新连接到mpd。重新连接后,我可以以某种方式再次执行with-block吗?

由于

1 个答案:

答案 0 :(得分:6)

简短的回答是你不能从上下文管理器中得到两次。您可以考虑使用装饰器来包装您尝试执行的内容,并在放弃之前重试并重新连接一定次数。这是一个简单的(非生产用途)示例,仅用于说明:

import mpd
import functools

HOST = "localhost"
PORT = 6600
mpdclient = mpd.MPDClient()
mpdclient.connect(HOST, PORT)

def withreconnect(retries=1):
    def _wrapper(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            for _ in range(retries + 1): # Loop retries + first attempt
                try:
                    return func(*args, **kwargs)
                except mpd.ConnectionError:
                    mpdclient.connect(HOST, PORT)
        return _wrapped
    return wrapped

@withreconnect() # Reconnect 1 time, default
def status():
    mpdclient.status()

@withreconnect(retries=3) # Reconnect 3 times
def lsinfo():
    mpdclient.lsinfo()

编辑:在无参数情况下添加对装饰器的调用