擅长:python、mysql、java
<p><a href="http://pythonhosted.org/asyncio_extras/#module-asyncio_extras.contextmanager" rel="noreferrer">asyncio_extras</a>包有一个很好的解决方案:</p>
<pre><code>import asyncio_extras
@asyncio_extras.async_contextmanager
async def smtp_connection():
client = SMTPAsync()
...
</code></pre>
<p>对于Python<;3.6,您还需要<a href="https://pypi.python.org/pypi/async_generator" rel="noreferrer">async_generator</a>包,并将<code>yield client</code>替换为<code>await yield_(client)</code>。</p>