python莫名其妙的yield, yield from, yield.send
练了几行代码,
慢慢找感觉。
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的更多相关文章
- Python天天美味(25) - 深入理解yield
Python天天美味(25) - 深入理解yield - CoderZh - 博客园 Python天天美味(25) - 深入理解yield yield的英文单词意思是生产,刚接触Python的时候 ...
- python 生成器、列表解析式、yield、迭代器
开局一张图总结关系 一.列表解析式 我们习惯生成列表通过list = [1, 2, 3]的方式.还有一种很方便的列表生成方式 list = [a*2 for a in range(10)],或者lis ...
- 深入理解yield(三):yield与基于Tornado的异步回调
转自:http://beginman.cn/python/2015/04/06/yield-via-Tornado/ 作者:BeginMan 版权声明:本文版权归作者所有,欢迎转载,但未经作者同意必须 ...
- 12.C#yield return和yield break及实际应用小例(六章6.2-6.4)
晚上好,各位.今天结合书中所讲和MSDN所查,聊下yield关键字,它是我们简化迭代器的关键. 如果你在语句中使用了yield关键字,则意味着它在其中出现的方法.运算符或get访问器是迭代器,通过使用 ...
- yield return 和 yield break
//yield return 返回类型必须为 IEnumerable.IEnumerable<T>.IEnumerator 或 IEnumerator<T>. static I ...
- Enumerator yielder.yield 与 Proc.yield 区别
最近看ruby cookbook遇到这个用法,google一下,这里原文解释 http://stackoverflow.com/questions/18865860/enumerator-yielde ...
- C#yield return和yield break
C#yield return和yield break 晚上好,各位.今天结合书中所讲和MSDN所查,聊下yield关键字,它是我们简化迭代器的关键. 如果你在语句中使用了yield关键字,则意味着它在 ...
- yield next和yield* next的区别
yield next和yield* next之间到底有什么区别?为什么需要yield* next?经常会有人提出这个问题.虽然我们在代码中会尽量避免使用yield* next以减少新用户的疑惑,但还是 ...
- Python学习之旅—生成器对象的send方法详解
前言 在上一篇博客中,笔者带大家一起探讨了生成器与迭代器的本质原理和使用,本次博客将重点聚焦于生成器对象的send方法. 一.send方法详解 我们知道生成器对象本质上是一个迭代器.但是它比迭代器对 ...
随机推荐
- Delphi 实现数字转大写
从网上找的一段代码 /// <summary> /// 小写转大写 /// </summary> /// <param name="mmje"> ...
- php魔术方法使用场景
php魔术方法-----__tostring(),__invoke,__call(),__callStatic ... __tostring(),__invoke() __tostring()方法是在 ...
- 【Codeforces717F】Heroes of Making Magic III 线段树 + 找规律
F. Heroes of Making Magic III time limit per test:3 seconds memory limit per test:256 megabytes inpu ...
- 1 云计算系列之云计算概述和KVM虚拟化简介
为什么会出现云之传统数据中学面临的问题 物理服务器的利用率非常低,浪费资源,且资源分配不合理,比如一台服务器CPU使用率不到40%,或者某个应用需要的硬件配置低但是服务器硬件配置高等等. 云计算概念 ...
- HDU 5167(map + 暴力)
题意:给出一个数n,问n能否是斐波那契数列中数的乘积 先刷选 斐波那契数列,然后就枚举 #include <cstdio> #include <cstring> #includ ...
- 深入浅出HTTP请求(转自http://www.cnblogs.com/yin-jingyu/archive/2011/08/01/2123548.html)
HTTP(HyperText Transfer Protocol)是一套计算机通过网络进行通信的规则.计算机专家设计出HTTP,使HTTP客户(如Web浏览器)能够从HTTP服务器(Web服务 器)请 ...
- Linux(Centos6.5)用户名密码
用户列表文件:/etc/passwd用户组列表文件:/etc/group 查看系统中有哪些用户:cut -d : -f 1 /etc/passwd查看可以登录系统的用户:cat /etc/passwd ...
- Bash 小问题【待更新】
bash 问题: 编写一个函数,用来返回某个目录下的目录个数.对于主目录下的所有目录,显示其属性信息,并把属性信息重定位到file_n(n=1.2.3)文件(第一个目录信息重定位到file_1, 第二 ...
- [Unity] Shader - CG语言 和 HLSL语言
CG 跟 HLSL几乎是一摸一样的. (HLSL官方参考,包含语法格式,函数库,关键字,在这个地方: http://msdn.microsoft.com/en-us/library/bb509638( ...
- JS各种方法
一.JS(去掉前后空格或去掉所有空格)的用法 1.去掉字符串前后所有空格:代码如下: function Trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ...