练了几行代码,

慢慢找感觉。

TASK,多线程,异步,很多地方都用到的呢。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from contextlib import contextmanager
from concurrent.futures import ThreadPoolExecutor

class Task:
    def __init__(self, gen):
        self._gen = gen

    def step(self, value=None, exc=None):
        try:
            if exc:
                fut = self._gen.throw(exc)
            else:
                fut = self._gen.send(value)
            fut.add_done_callback(self._wakeup)
        except StopIteration as exc:
            pass

    def _wakeup(self, fut):
        try:
            result = fut.result()
            self.step(result, None)
        except Exception as exc:
            self.step(None, exc)

def func(x, y):
    'Some function. Nothing too interesting'
    import time
    time.sleep(2)
    return x + y

def do_func(x, y):
    try:
        result = yield pool.submit(func, x, y)
        print("Got: ", result)
    except Exception as e:
        print("Failed: ", repr(e))

def do_many(n):
    while n > 0:
        result = yield pool.submit(func, n, n)
        print("Got: ", result)
        n -= 1

def after(delay, gen):
    yield from pool.submit(time.sleep, delay)
    yield from gen
    print("GOOOOT: ", result)
    '''
    result = None
    try:
        while True:
            f = gen.send(result)
            result = yield f
        # print("GOOOT: ", result)
    except StopIteration:
        pass
    print("GOOOT: ", result)
    '''

pool = ThreadPoolExecutor(max_workers=8)
# fut = pool.submit(func, 2, 3)
# r = fut.result()
# print('Got:', r)

t = Task(do_func(2, 3))
t.step()
t = Task(do_func(2, "Hello"))
t.step()
Task(after(3, do_func(2, 3))).step()
t = Task(do_many(10))
t.step()

def countdown(n):
    print ("Counting down from ", n)
    while n > 0:
        yield n
        n -= 1

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

@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.")

g = grep("python")
g.send("Yeah, but no, but yeah")
g.send("python generatores rock!")
g.close()

def receiver():
    while True:
        item = yield
        print("Got ", item)

recv = receiver()
next(recv)
recv.send("hello")
recv.send("world")

def chain(x, y):
    yield from x
    yield from y

a = [1, 2, 3]
b = [4, 5, 6]
for x in chain(a, b):
    print(x, end=" ")

python莫名其妙的yield, yield from, yield.send的更多相关文章

  1. Python天天美味(25) - 深入理解yield

    Python天天美味(25) - 深入理解yield - CoderZh - 博客园 Python天天美味(25) - 深入理解yield   yield的英文单词意思是生产,刚接触Python的时候 ...

  2. python 生成器、列表解析式、yield、迭代器

    开局一张图总结关系 一.列表解析式 我们习惯生成列表通过list = [1, 2, 3]的方式.还有一种很方便的列表生成方式 list = [a*2 for a in range(10)],或者lis ...

  3. 深入理解yield(三):yield与基于Tornado的异步回调

    转自:http://beginman.cn/python/2015/04/06/yield-via-Tornado/ 作者:BeginMan 版权声明:本文版权归作者所有,欢迎转载,但未经作者同意必须 ...

  4. 12.C#yield return和yield break及实际应用小例(六章6.2-6.4)

    晚上好,各位.今天结合书中所讲和MSDN所查,聊下yield关键字,它是我们简化迭代器的关键. 如果你在语句中使用了yield关键字,则意味着它在其中出现的方法.运算符或get访问器是迭代器,通过使用 ...

  5. yield return 和 yield break

    //yield return 返回类型必须为 IEnumerable.IEnumerable<T>.IEnumerator 或 IEnumerator<T>. static I ...

  6. Enumerator yielder.yield 与 Proc.yield 区别

    最近看ruby cookbook遇到这个用法,google一下,这里原文解释 http://stackoverflow.com/questions/18865860/enumerator-yielde ...

  7. C#yield return和yield break

    C#yield return和yield break 晚上好,各位.今天结合书中所讲和MSDN所查,聊下yield关键字,它是我们简化迭代器的关键. 如果你在语句中使用了yield关键字,则意味着它在 ...

  8. yield next和yield* next的区别

    yield next和yield* next之间到底有什么区别?为什么需要yield* next?经常会有人提出这个问题.虽然我们在代码中会尽量避免使用yield* next以减少新用户的疑惑,但还是 ...

  9. Python学习之旅—生成器对象的send方法详解

    前言 在上一篇博客中,笔者带大家一起探讨了生成器与迭代器的本质原理和使用,本次博客将重点聚焦于生成器对象的send方法. 一.send方法详解  我们知道生成器对象本质上是一个迭代器.但是它比迭代器对 ...

随机推荐

  1. IOS在自己网站发布APP(企业版$299上线流程)

    最近刚上线一个企业内部应用,前期准备账号和后期上线过程发现网络上的资源不是非常全面,在这里写给大家分享一下我的发布过程 首先是企业账号的申请我们企业账号前前后后一共花了16天时间,由于公司各方面都非常 ...

  2. Nginx基本使用

    Nginx基本使用 下载源码包http://nginx.org/ http://nginx.org/en/download.html yum -y install pcre-devel openssl ...

  3. BZOJ 1861: [Zjoi2006]Book 书架

    1861: [Zjoi2006]Book 书架 Time Limit: 4 Sec  Memory Limit: 64 MBSubmit: 1290  Solved: 740[Submit][Stat ...

  4. 【Codeforces717G】Underfail Hash + 最大费用最大流

    G. Underfail time limit per test:1 second memory limit per test:256 megabytes input:standard input o ...

  5. BZOJ3505 [Cqoi2014]数三角形

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...

  6. RabbitMQ 实现RPC

    实现RPC 首先要弄明白,RPC是个什么东西. (RPC) Remote Procedure Call Protocol 远程过程调用协议 在一个大型的公司,系统由大大小小的服务构成,不同的团队维护不 ...

  7. 数据结构作业——hash(字符串哈希)

    Hash Description 给定长度为 n ( n<=1000000)的字符串,字符串仅由小写字母的前 m ( m<=6) 个字符组成,请你计算出共有多少长度为 k( k<=6 ...

  8. WEKA使用

    参考 http://bbs.middleware123.com/thread-24052-1-1.html  使用Weka进行数据挖掘 http://quweiprotoss.blog.163.com ...

  9. CSS 概念 & 作用

    http://www.cnblogs.com/moveofgod/archive/2012/09/18/2691101.html 式样定义   如何显示 HTML内容 通常存储在式样表中 作用 : 解 ...

  10. 创建NetWorkDataset---FileGDB篇

    /// <summary> /// 创建NetWorkDataset /// </summary> /// <returns>INetworkDataset.< ...