Reputation: 41
I have been banging my head against the wall with this for some time now and I am not really sure how to deal with it properly.
I have a simple test.py script
import asyncio
print(f'{asyncio.get_event_loop()}')
print(f'{asyncio.get_event_loop_policy()}')
When I run this in iPython, jupyter qtconsole or jupyter notebook, the output is as follows:
<_WindowsSelectorEventLoop running=True closed=False debug=False>
<asyncio.windows_events.WindowsSelectorEventLoopPolicy object at 0x0000029DE7A96D30>
However, when the very same script is run from the command line (PowerShell) on the same machine with "python test.py", I get:
<ProactorEventLoop running=False closed=False debug=False>
<asyncio.windows_events.WindowsProactorEventLoopPolicy object at 0x000001C666186E20>
Obviously, asyncio does something different to set up the default event loop depending on the context, but I don't understand why and how. Furthermore, the main problem is that the event loop is running in the former case and not running in the latter. This causes runtime errors in scripts that use asyncio functionality, but only if they are run from the command line and not otherwise.
Needless to say, this is baffling and troubling behaviour. I am loath to come up with workarounds for something like this, as it just seems too bizarre. I am using Python 3.9.4 on Windows 11.
Does anybody have ideas of how to best deal with this or have dealt with this in the past?
Upvotes: 0
Views: 734
Reputation: 41
I've found a trivial solution for this.
Basically, as suggested by Tim, you just need to wrap whatever asyncio call that ends up causing the Runtime Error: no running event loop
in a dummy coro and then use asyncio.run()
on it. This has the effect of creating an event loop for the specific duration that you need.
Upvotes: 0
Reputation: 54698
Jupyter is a Windows GUI application, which already has a Windows event loop, and asyncio
has to negotiate with that. PowerShell is a command-line host, where apps do not get an automatic event loop. Thus, asyncio
has to provide one.
You should be able to use asyncio.run()
in either case.
Upvotes: 1