Asyncio doesn't work in pythonista 3
I've just purchased pythonista 3 and I'm trying to run the following code straight from the docs:
import asyncio async def hello_world(): print("Hello World!") loop = asyncio.get_event_loop() # Blocking call which returns when the hello_world() coroutine is done loop.run_until_complete(hello_world()) loop.close()
I get the error: RuntimeError: There is no current event loop in thread 'Dummy-1'.
Am I doing something wrong?
Asyncio does work in Pythonista. If you double click the home button and throw Pythonista 3 out of memory and then relaunch Pythonista 3 and rerun your script, it will work.
My advise is that you comment out the line
loop.close()and then you will be able to run your asyncio script multiple times in a single Pythonista session.
Great, that workaround does sort it out in the meantime. Thank you for reporting the bug for me :)
loop = asyncio.get_event_loop_policy().new_event_loop()
I am confused. The issue was closed as ”fixed”, while all examples everywhere use
get_event_loopand fail with the error stating
There is no current event loop in thread 'Dummy-1'.
Why is this not an issue with Pythonista?
As I understand things, the code above does work, the first time it is run.
But, because the pythonista environment is not fully reset when running a new script, the default event loop is now closed. This would be same as if you ran this code multiple times in IDLE for example, without python exiting. So bot so much a bug, as a subtlety with operating in a interactive environment. Other examples of things like this, include
loggingloggers dont get cleared out, which is a good thing sometimes but also mean your code needs to check for existing handlers before adding new ones.
What users can do is use
after loop.close, to reset the default event loop. Then get_event_loop works again. In theory, this could go into pythonista_preflight.py, however it is not obvious to me this wouldnt cause other issues, or would really be the intended behavior.
@JonB, thanks, that clarifies things.
@JonB, maybe some of these errors come from Pythonista running UI in separate thread, which does not know about the loop unless I provide it specifically. Need to experiment.