您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

python中的协程(协同程序)

2024/4/17 0:04:43发布10次查看
协程:将函数编写为一个能处理输入参数的任务
使用yield语句并以表达式yield的形式创建协程
#匹配器案例:
def print_info(data): print('looking for',data); while true: line = (yield) if data in line: print(line);
上面这个函数 就是一个协程程序 要使用这个函数 首先需用调用它 并且 向前执行到第一条yield语句
info = print_info('python'); info.__next__(); #向前执行第一条yield语句
输出结果:
looking for python
然后使用send方法发送数据给协同程序进行处理
info.send('hell world'); info.send('this is python'); info.send('python goods');
如果 发送的数据中含有data参数值 则匹配成功 返回该条数据
输出结果:
looking for python
this is python
python goods
send()为协程发送值时 程序处于暂时中止状态 当发送值后 yield表达式将返回这个值,后面的程序对返回值进行处理 直到遇到下一个表达式 结束 这个过程将持续运行直到协程函数返回或者调用close方法
基于一部分程序生成的数据会被程序的另一部分使用(生产者-使用者模式)
编写并发程序时,协程作用很明显 他代表数据的一个使用者
info =[ print_info('python'), print_info('hello'), print_info('chunrui') ]
通过调用__next__()准备所有的匹配器
for n in info: n.__next__();
定义一个函数获取文件中每列数据并且传递给生成器
def tail(f): for line in f : if not line: time.sleep(0.1); continue; #如果不存在 则推迟0.1s 进行下一次 yield line; mylist = tail(open('e:/work.txt'))
循环mylist中的值 然后send给协程程序
for m in mylist: for n in info: n.send(m);
输出结果:
looking for python looking for hello looking for chunrui python is conputer language chunrui is name hello world is the first case i like to use python my name is chunrui
总结:
1,协程:协同程序 能处理输入的参数的任务函数 当协程暂停时 我们从其中获取到返回值 当调用回到程序中时 能够传入额外或者新的参数 仍然能够从上次离开的地方继续
2,使用send函数为协程发送参数
以上就是python中的协程(协同程序)的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录