{"id":954,"hash":"b1f6bcbcb1e6c2abebbae66a3f8c525f9df54e9fdf02dd2d694064bfb9e35300","pattern":"Error &quot;RuntimeError: This event loop is already running&quot; in Python","full_message":"I think I'm getting this error, because my code calls asyncio.get_event_loop().run_until_complete(foo()) twice.  Once from foo() and the second time from a function called by foo(). Why should this be a problem? Why should I even care that this loop is running?\n\nI'm not surprised by the fact that the error is raised.  I can trace it back to the asyncio source and see that the authors of this library wanted to do it this way, and there isn't any mystery there.  The puzzling part is in the reason the authors of the library decided it's illegal to ask from the event loop to run some function to completion when the loop is already running.\n\nWe can reduce the problem to just two such calls, and through a case analysis, we will see that these are the three possibilities:\n\nNeither of both functions ever terminates.\nOne of the functions eventually terminates.\nBoth functions eventually terminate.\n\nNow, is there any sane behavior which would address all three cases?  To me, it is obvious that there is, or, perhaps are multiple sane behaviors possible here.  For example:\n\nNothing special. The execution of both functions is interleaved, and they keep running forever, just as expected.\nThe loop doesn't return control to the code following the first instance of run_until_complete() until the second function completes (thus no code after run_until_complete() will be executed.\nAfter the last function terminates, the loop returns control to the first code object which invoked run_until_complete, ignoring all other invocation sites.\n\nNow, I can understand that this behavior may not be something that everyone would want.  But, since this library decided to give programmers control over starting / stopping the event loop, it should also meet the consequences of such decisions.  Making it an error to start the same loop multiple times precludes library code from ever doing this, which reduces the quality and usefulness of libraries utilizing asyncio (which is indeed the case with, for example, aiohttp).","ecosystem":"pypi","package_name":"python-asyncio","package_version":null,"solution":"I got the issue resolved by using the nest_async\n\npip install nest-asyncio\n\nAnd by adding the below lines in my file.\n\n# The __import__ line is not needed. I am leaving it just\n# so that the comments make sense\n# __import__('IPython').embed()\nimport nest_asyncio\n\nnest_asyncio.apply()","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/46827007/error-runtimeerror-this-event-loop-is-already-running-in-python","votes":191,"created_at":"2026-04-19T04:52:05.806787+00:00","updated_at":"2026-04-19T04:52:05.806787+00:00"}