擅长:python、mysql、java
<p><a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.run" rel="nofollow noreferrer">^{<cd1>}</a>。。。你知道吗</p>
<blockquote>
<p>[...] creates a new event loop and closes it at the end. [...]</p>
</blockquote>
<p>在执行<code>main</code>期间,用<code>task</code>包装的coro没有机会完成。<br/>
如果返回<code>Task</code>对象并打印它,您将看到它处于取消状态:</p>
<pre><code>async def main():
task = asyncio.create_task(Slowpoke())
# return "Hi!"
return task
if __name__ == "__main__":
print(asyncio.run(main()))
# I see you shiver with antici...
# <Task cancelled coro=<Slowpoke() done, defined at [...]>>
</code></pre>
<p>在创建和安排任务(并打印'Hi!')之后<code>main</code>结束时,事件循环将关闭,这将导致其中所有正在运行的任务被取消。你知道吗</p>
<p>您需要保持事件循环运行,直到任务完成为止,例如,通过<code>await</code>将其放入<code>main</code>:</p>
<pre><code>async def main():
task = asyncio.create_task(Slowpoke())
await task
return task
if __name__ == "__main__":
print(asyncio.run(main()))
# I see you shiver with antici...
# ...pation!
# <Task finished coro=<Slowpoke() done, defined at [..]> result=None>
</code></pre>