23313 发表于 2016-5-11 09:52:08

python中的协程(协同程序)

协程:将函数编写为一个能处理输入参数的任务
使用yield语句并以表达式yield的形式创建协程
#匹配器案例:


1
2
3
4
5
6
def print_info(data):
   print('Looking for',data);
   while True:
   line = (yield)
   if data in line:
       print(line);




上面这个函数 就是一个协程程序 要使用这个函数 首先需用调用它 并且 向前执行到第一条yield语句



1
2
info = print_info('python');
info.__next__();#向前执行第一条yield语句




输出结果:
Looking for python

然后使用send方法发送数据给协同程序进行处理

1
2
3
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方法
基于一部分程序生成的数据会被程序的另一部分使用(生产者-使用者模式)
编写并发程序时,协程作用很明显 他代表数据的一个使用者

1
2
3
4
5
info =[
    print_info('python'),
    print_info('hello'),
    print_info('chunrui')
]






通过调用__next__()准备所有的匹配器

1
2
for n in info:
n.__next__();






定义一个函数获取文件中每列数据并且传递给生成器


1
2
3
4
5
6
7
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给协程程序

1
2
3
for m in myList:
for n in info:
    n.send(m);






输出结果:
Looking for python
Looking for hello
Looking for chunrui

python isconputer language
chunrui is name
hello world is the first case
I like to use python
myname is chunrui
总结:
      1,协程:协同程序能处理输入的参数的任务函数 当协程暂停时 我们从其中获取到返回值当调用回到程序中时 能够传入额外或者新的参数 仍然能够从上次离开的地方继续

      2,使用send函数为协程发送参数
页: [1]
查看完整版本: python中的协程(协同程序)