How to use multiple event loops in a Python Program
Background
This article describes how to use multiple event loops in a Python program. The following structure is often used in Python asynchronous programming:
import asyncioasync def doAsync(): await asyncio.sleep(0) #...if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(doAsync()) loop.close()
This is certainly good, but when you use loop for the second time, the program will throw an exception.RuntimeError: Event loop is closed
This is understandable. The ideal program should also solve various asynchronous IO problems in a time loop.
However, in the terminal environment such as Ipython, it is too troublesome to re-open the terminal every time if you want to write an asynchronous program for Python. At this time, it is necessary to find a better solution.
Solution
We can useasyncio.new_event_loop
Function to create a new event loop and useasyncio.set_event_loop
Set the global event loop. At this time, you can run the asynchronous event loop multiple times, but it is best to save the defaultasyncio.get_event_loop
And restore it back at the end of the event loop.
In the end, our code is like this.
Code
import asyncioasync def doAsync(): await asyncio.sleep(0) #...def runEventLoop() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(doAsync()) loop.close()if __name__ == "__main__": oldloop = asyncio.get_event_loop() runEventLoop() runEventLoop() asyncio.set_event_loop(oldloop)
Feelings
The event loop is to do a lot of things together. In the official Python code, it is better to use only one default event loop. It is free to study and practice normally.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.