How to use multiple event loops in a Python Program

Source: Internet
Author: User

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 closedThis 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_loopFunction to create a new event loop and useasyncio.set_event_loopSet 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_loopAnd 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.