yield

yield能将一个函数转换成 generator(生成器),它只能通过调用next()/send()才开始执行,执行到每一个yield语句就会中断,交出执行权,并返回一个迭代值,下次执行从yield中断处可以通过send()接收一个参数并继续执行。
send与next的不同是send可以传值到yield语句的左边。例如

1
2
3
def test():
...
arg = yield n
使用test().send(1)时,test函数会将此时的n返回且将1赋值给arg
但是注意在第一次调用test函数时如果使用test().send(1)会报错,因为第一次调用时应将函数中断在yield语句处,即使用test().next()或者是test.send(None)

next

eg.1

1
2
3
4
5
6
7
8
9
10
import asyncio

def test():
yield 1
yield 2

if __name__=='__main__':
func = test()
print(next(func))
print(next(func))
1
2
1
2

eg.2

1
2
3
4
5
6
7
8
9
10
import asyncio

def test():
arg = yield 1
yield arg

if __name__=='__main__':
func = test()
print(next(func))
print(next(func))
1
2
1
None

send

eg.1

1
2
3
4
5
6
7
8
9
10
import asyncio

def test():
arg = yield 1
yield arg

if __name__=='__main__':
func = test()
print(func.send(None))
print(func.send(100))
1
2
1
100

eg.2

1
2
3
4
5
6
7
8
9
10
import asyncio

def test():
yield 1
yield 2

if __name__=='__main__':
func = test()
print(func.send(None))
print(func.send(100))
1
2
1
2

eg.3

1
2
3
4
5
6
7
8
9
10
import asyncio

def test():
yield 1
yield 2

if __name__=='__main__':
func = test()
print(func.send(50))
print(func.send(100))
1
2
3
4
Traceback (most recent call last):
File "d:\cheng.dongquan\Working\Ocpp\test.py", line 9, in <module>
print(func.send(2))
TypeError: can't send non-None value to a just-started generator

yield from

目前就只给一个简单的案例。
在下面他相当于时一个中间件:

1
2
3
4
5
6
7
8
9
10
11
import asyncio

def test():
yield 1
yield 2
def main():
yield from test()
if __name__=='__main__':
func = main()
print(next(func))
print(next(func))
1
2
1
2

asyncio

参考廖雪峰的官方网站 ## async/await

1
2
3
4
5
6
7
8
9
10
11
12
import threading
import asyncio

async def hello():
print('Hello world! (%s)' % threading.currentThread())
await asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
1
2
3
4
5
Hello world! (<_MainThread(MainThread, started 140735195337472)>)
Hello world! (<_MainThread(MainThread, started 140735195337472)>)
(暂停约1秒)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)

aiohttp

pass