


Detailed explanation of python generator coroutine operation with examples
The following editor will bring you an example of python generator coroutine operation. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
1. Yield operation method
We define a generator as follows:
def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) while True: goods = yield print("货物[%s]已经被%s搬进仓库了。"%(goods,name)) p = put_on("bigberg") #输出 G:\python\install\python.exe G:/python/untitled/study4/test/double.py Process finished with exit code 0
When we convert a function into a generator through yield, no result will be returned when running the function directly. Because the function is already a generator at this time, we need to get the value through next(), and jump out of the function again when yield is encountered.
print(type(p)) #输出 <class 'generator'>
We add the next() method:
def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) while True: goods = yield #遇到yield中断 print("货物[%s]已经被%s搬进仓库了。"%(goods,name)) #中断后运行部分 p = put_on("bigberg") p.__next__() #输出 Hi bigberg, 货物来了,准备搬到仓库!
At this time, the function interrupts at the place where goods = yield, When we call the next() function again, the function will only run the content after the interruption, that is, the part below yield in the above example.
We add another next():
def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) while True: goods = yield print("货物[%s]已经被%s搬进仓库了。"%(goods,name)) p = put_on("bigberg") p.__next__() p.__next__() #输出 Hi bigberg, 货物来了,准备搬到仓库! 货物[None]已经被bigberg搬进仓库了。
We can run next() for the second time part of the content below yield, but it does not Pass a value to goods, so goods is None.
Summary:
Convert the function into a generator through yield, you need to use the next() method to run
yield Just retain the interrupt status of the function, and calling next() again will execute the part after yield
If yield does not return a value, it will return a None value
2. Send() passes value
##
def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) while True: goods = yield print("货物[%s]已经被%s搬进仓库了。"%(goods,name)) p = put_on("bigberg") p.__next__() p.send("瓜子") #输出 Hi bigberg, 货物来了,准备搬到仓库! 货物[瓜子]已经被bigberg搬进仓库了。
Summary:
__next__() just calls this yield, which can also be said to wake up the yield, but it does not pass the value to the yield. The send() method calls yield and can pass a value to yieldYou must use __next__() before using the send() function, because it needs to be interrupted first. When it is called for the second time, Only then can the value be passed.def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) while True: goods = yield print("货物[%s]已经被%s搬进仓库了。"%(goods,name)) p = put_on("bigberg") p.__next__() p.send("瓜子") p.send("花生") p.send("饼干") p.send("牛奶") #多次调用send() Hi bigberg, 货物来了,准备搬到仓库! 货物[瓜子]已经被bigberg搬进仓库了。 货物[花生]已经被bigberg搬进仓库了。 货物[饼干]已经被bigberg搬进仓库了。 货物[牛奶]已经被bigberg搬进仓库了。
3. Single thread to achieve parallel effect (coroutine)
import time def put_on(name): print("Hi {}, 货物来了,准备搬到仓库!".format(name)) while True: goods = yield print("货物[%s]已经被%s搬进仓库了。"%(goods,name)) def transfer(name): p = put_on('A') p2 = put_on('B') p.__next__() p2.__next__() print("%s将货物送来了!"%name) for i in range(5): time.sleep(1) print("%s递过来两件货物"%name) p.send("瓜子") p2.send("花生") transfer("bigberg") #输出 Hi A, 货物来了,准备搬到仓库! Hi B, 货物来了,准备搬到仓库! bigberg将货物送来了! bigberg递过来两件货物 货物[瓜子]已经被A搬进仓库了。 货物[花生]已经被B搬进仓库了。 bigberg递过来两件货物 货物[瓜子]已经被A搬进仓库了。 货物[花生]已经被B搬进仓库了。 bigberg递过来两件货物 货物[瓜子]已经被A搬进仓库了。 货物[花生]已经被B搬进仓库了。 bigberg递过来两件货物 货物[瓜子]已经被A搬进仓库了。 货物[花生]已经被B搬进仓库了。 bigberg递过来两件货物 货物[瓜子]已经被A搬进仓库了。 货物[花生]已经被B搬进仓库了。
The above is the detailed content of Detailed explanation of python generator coroutine operation with examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

MinIO Object Storage: High-performance deployment under CentOS system MinIO is a high-performance, distributed object storage system developed based on the Go language, compatible with AmazonS3. It supports a variety of client languages, including Java, Python, JavaScript, and Go. This article will briefly introduce the installation and compatibility of MinIO on CentOS systems. CentOS version compatibility MinIO has been verified on multiple CentOS versions, including but not limited to: CentOS7.9: Provides a complete installation guide covering cluster configuration, environment preparation, configuration file settings, disk partitioning, and MinI

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

When installing PyTorch on CentOS system, you need to carefully select the appropriate version and consider the following key factors: 1. System environment compatibility: Operating system: It is recommended to use CentOS7 or higher. CUDA and cuDNN:PyTorch version and CUDA version are closely related. For example, PyTorch1.9.0 requires CUDA11.1, while PyTorch2.0.1 requires CUDA11.3. The cuDNN version must also match the CUDA version. Before selecting the PyTorch version, be sure to confirm that compatible CUDA and cuDNN versions have been installed. Python version: PyTorch official branch

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
