练了几行代码,

慢慢找感觉。

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. Couchbase的安装步骤

    本指南将在几分钟内让你上手,探索关联APP,在命令行shell 中删除一些实例查询,并尝试查询工作台. 下载Couchbase Server 下载地址:http://www.couchbase.com ...

  2. Android中Shape的使用

    先看一下文档对Shape Drawable的描述: Shape Drawable An XML file that defines a geometric shape, including color ...

  3. bzoj3527: [Zjoi2014]力

    #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...

  4. CSS实现正方体旋转

    代码如下: <!DOCTYPE html><html lang="en"><head>    <meta charset="UT ...

  5. __index

    Window = {} Window.prototype = {x = , y = , width = , height = } Window.mt = {} function Window.new( ...

  6. AXIS 调用 webservice服务时传递 服务器验证需要的用户名密码

    System.setProperty("javax.net.ssl.trustStore", T.class.getResource(".").getPath( ...

  7. Redis常用命令

    Redis常用命令Redis提供了丰富的命令对数据库和各种数据类型进行操作,这些命令可以再Linux终端使用.1.键值相关命令2.服务器相关命令 一.键值相关命令 1.get get 键值 当 key ...

  8. Java多线程编程核心技术---学习分享

    继承Thread类实现多线程 public class MyThread extends Thread { @Override public void run() { super.run(); Sys ...

  9. 关于Visual Studio 2015中没有报表项(ReportViewer)的解决方案。

    没有报表,一般默认安装之后会出现这种情况,在安装的时候选择自定义安装,把Microsoft Office 开发人员工具.Microsoft SQL Server Data Tools勾选上,安装之后就 ...

  10. 使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束

    简要分析: 要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中.同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来 ...