問題
asyncio.run_until_complete() を使用して async def 関数を実行しようとすると (例):
asyncio_example.py
import asyncio
asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))次のようなエラーメッセージが表示されます:
asyncio_runtimeerror_example.txt
Cell In[3], line 15
12 raise
14 # Usage example:
---> 15 asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))
File /usr/lib/python3.12/asyncio/base_events.py:663, in BaseEventLoop.run_until_complete(self, future)
652 """Run until the Future is done.
653
654 If the argument is a coroutine, it is wrapped in a Task.
(...)
660 Return the Future's result, or raise its exception.
661 """
662 self._check_closed()
--> 663 self._check_running()
665 new_task = not futures.isfuture(future)
666 future = tasks.ensure_future(future, loop=self)
File /usr/lib/python3.12/asyncio/base_events.py:622, in BaseEventLoop._check_running(self)
620 def _check_running(self):
621 if self.is_running():
--> 622 raise RuntimeError('This event loop is already running')
623 if events._get_running_loop() is not None:
624 raise RuntimeError(
625 'Cannot run the event loop while another loop is running')
RuntimeError: This event loop is already running解決策
loop.run_until_complete() を使用する代わりに、asyncio.create_task() を使用してコルーチンを実行します:
asyncio_create_task.py
future = asyncio.get_event_loop().create_task(asyncio.sleep(1))オプションで、future を await してコルーチンの完了を待つことができます:
asyncio_await_future.py
await futureこれは、loop.run_until_complete() が同期コード向けであり、常に ループを開始するためです。そのため、ループが既に実行されている場合は失敗します。
通常、このエラーは Jupyter Notebook のようなコンテキストでコードを実行している場合に発生します (内部でイベントループを開始するため)。純粋な Python スクリプトなど、別のコンテキストで実行したい場合は、コードを変更する必要があるかもしれません。
同じカテゴリの類似記事をチェック:
Python
この記事が役に立った場合は、TechOverflow での新しい記事の調査と公開を支援するため、「Buy Me a Coffee」でのご支援、または PayPal 経由でのご寄付をご検討ください