import asyncio
import aiomysql
import logging

'''
def fab():
    n, a, b = 0, 0, 1
    while n < 10:
        print(n, a, b)
        yield b
        a, b = b, a + b
        n = n + 1

numbers = fab()
# for num in numbers:
#     print(num)


def htest():
    i = 1
    while i < 4:
        n = yield i
        if i == 3:
            return 100
        i += 1

# 生成器必须用 yield 返回数据，不然会抛出 StopIteration 异常
def itest():
    # var 接收 到的值 是 htest 生成器中  return 返回的值 （使用 yield from 获取）
    val = yield from htest()
    print(val)
    yield val

t = itest()
t.send(None)
j = 0

while j < 3:
    j += 1
    try:
        t.send(j)
    except StopIteration as e:
        print('异常了')

def g(x):
    yield from range(x, 0, -1)
    yield from range(x)

gg = g(5)
# print(gg.__next__())
print(list(gg))


def accumulate():
    tally = 0
    while 1:
        next = yield
        print(next)
        if next is None:
            return tally
        tally += next

def gather_tallies(tallies):
    while 1:
        tally = yield from accumulate()
        tallies.append(tally)
        print("执行了几次")

tallies = []
acc = gather_tallies(tallies)
next(acc)
# print("执行了N次")
for i in range(4):
    acc.send(i)

acc.send(None)
print(tallies)

for i in range(5):
    acc.send(i)
acc.send(None)
print(tallies)

 # grep.py
#
# A very simple coroutine

def coroutine(func):
    def start(*args, **kwargs):
        cr = func(*args, **kwargs)
        cr.__next__()
        return cr
    return start

# 给一个函数定义生成器标识
# @coroutine
# def grep(pattern):
#     print("Looking for %s" % pattern)
#     while True:
#         line = (yield)
#         if pattern in line:
#             print(line)
@coroutine
def grep(pattern):
    print("Looking for %s" % pattern)
    try:
        while True:
            line = (yield)
            if pattern in line:
                print(line),
    except GeneratorExit:
        print('Going away. Goodbye')

# Example use
if __name__ == '__main__':
    g = grep("python")
    # g.__next__()    # 调用 .__next__() 将函数grep(pattern) 变成一个 生成器
    # g.send("Yeah, but no, but yeah, but no")
    # g.send("A series of tubes")
    g.send("python generators rock!")
    g.close()
'''

'''
def countdown(n):
    print('Counting down from', n)
    while n >= 0:
        newvalue = (yield n)
        print('newvalue: %s' % newvalue)
        # if a new value got sent in, reset n with it
        if newvalue is not None:
            n = newvalue
        else:
            n -= 1


c = countdown(5)
for x in c:
    print('x : %s' % x)
    if x==5:
        c.send(3)

 '''

import time

def coroutine(func):
    def start(*args, **kwargs):
        cr = func(*args, **kwargs)
        cr.__next__()
        return cr
    return start


@coroutine
def follow(thefile, target):
    thefile.seek(0, 2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
        target.send(line)

@coroutine
def grep(pattern, target): #filter 过滤结果
    while True:
        line = (yield)
        if pattern in line:
            target.send(line)

@coroutine
def printer():
    while True:
        line = (yield)
        print(line)

@coroutine
def broadcast(targets):
    while True:
        item = (yield)
        for target in targets:
            target.send(item)


if __name__ == '__main__':
    f = open('access-log')
    broadcasts = [
        broadcast[grep('python', printer)],
        broadcast[grep('pyl', printer)],
        broadcast[grep('swig', printer)]
    ]
    follow(f, broadcasts)

'''
follow 函数中 将 line 传入 broadcast
broadcast 函数中将 item 传入 grep 中
grep 函数再将 line  传入 printer
printer 获取传入的 line ， 将结果打印出来
'''

'''
class Book(Model):
    __table__ = 'book'

    id = IntegerField(primary_key=True)
    name = StringField()
    user_id = IntegerField()


book = Book(id=9, name='时间简史', user_id=3)

# loop = asyncio.get_event_loop()
# loop.run_until_complete(create_pool(host='127.0.0.1', port=3306, user='root', password='qq5591916', db='YLM', loop=loop))
# rs = loop.run_until_complete(Book.find(1))
# print('heh: %s' % rs)

# u = User(id=123, name='ZhouXiaorui')

loop = asyncio.get_event_loop()
loop.run_until_complete(create_pool(user='root', password='qq5591916', db='YLM', loop=loop))
rs = loop.run_until_complete(book.remove())
print('heh: %s' % rs)
'''