python生成器与协程

点击量:7

贴一段代码:
这段代码分别是用协程与生成器写的;

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 xiuhao <xiuhao@xiuhaodeMacBook-Pro.local>
#
"""
"""
import time
def loop():
    ser = "test"
    command = ''
    print '[loop] run loop...'
    while True:
        command = yield ser
        if command == '':
            print '[loop] run something...'
        elif command == 'change':
            ser = "[loop] test_change"
        else:
            ser = "[loop] stop"
            break
    yield ser
def control(l):
    l.send(None)
    n = 0
    while n < 5:
        n = n + 1
        time.sleep(1)
        ser = l.send('change')
        print "[control] ser:", ser
    ser = l.send('stop')
    l.close()
    print "[control] ser:", ser
def loop2():
    ser = "test"
    command = ''
    print 'run loop...'
    o = control2()
    while True:
        command = next(o)
        # print '[loop2] command: ', command
        if command == '':
            print '[loop2] run something...'
        elif command == 'change':
            ser = "[loop2] test_change"
            print ser
        else:
            ser = "[loop2] stop"
            print ser
            break
def control2():
    n = 0
    while n < 5:
        n = n+1
        time.sleep(1)
        ser = 'change'
        print "[control2] send: ", ser
        yield ser
    ser = 'stop'
    yield ser
if __name__ == '__main__':
    # l = loop()
    # control(l)
    # print '--------------------'
    loop2()

协程这个特性相比仅仅使用生成器,有一个很神奇的地方,就是多出一个Send方法,将
yield这个操作返回值,使得生成器可以接收数据,并将这个数据通过yield返回生成器
内部。通过这个方法,可以比较巧妙地把一些参数扔进已经处于循环状态的函数,而不
需要使用别的类似于signal的变量,十分方便。

发表评论

电子邮件地址不会被公开。 必填项已用*标注