https://juejin.im/post/5b3f540af265da0f742ec5e1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

import asyncio
import sys

def set_loop():
"""Attempt to use uvloop. 更快的事件轮询"""
import asyncio
from asyncio.events import BaseDefaultEventLoopPolicy

policy = None

if sys.platform == 'win32':
if hasattr(asyncio, 'WindowsProactorEventLoopPolicy'):
# pylint: disable=no-member
policy = asyncio.WindowsProactorEventLoopPolicy()
else:
class ProactorPolicy(BaseDefaultEventLoopPolicy):
"""Event loop policy to create proactor loops."""

_loop_factory = asyncio.ProactorEventLoop

policy = ProactorPolicy()
else:
try:
import uvloop
except ImportError:
pass
else:
policy = uvloop.EventLoopPolicy()

if policy is not None:
asyncio.set_event_loop_policy(policy)

async def slow_operation(n):
await asyncio.sleep(n)
print('Slow operation {} complete'.format(n))
return n
all_tasks = [
asyncio.ensure_future(
slow_operation(1)
),
slow_operation(2),
slow_operation(9),
slow_operation(2),
slow_operation(1),
slow_operation(2),
slow_operation(3),
]

set_loop()
loop = asyncio.get_event_loop()
dones, pendings = loop.run_until_complete(asyncio.wait( all_tasks ))
for fut in dones:
print("return value is {}".format(fut.result()))


# results = await asyncio.gather(*all_tasks)
# for result in results:
# print('Task ret: ', result)
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Slow operation 1 complete
Slow operation 1 complete
Slow operation 2 complete
Slow operation 2 complete
Slow operation 2 complete
Slow operation 3 complete
Slow operation 9 complete


return value is 2
return value is 1
return value is 2
return value is 1
return value is 9
return value is 3
return value is 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import  asyncio

try:
# pylint: disable=invalid-name
asyncio_run = asyncio.run # type: ignore
except AttributeError:

def asyncio_run(main, debug=False):
"""Minimal re-implementation of asyncio.run (since 3.7)."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.set_debug(debug)
try:
return loop.run_until_complete(main)
finally:
asyncio.set_event_loop(None)
loop.close()

async def slow_operation_1(m):
await asyncio.sleep(m)
print('Slow operation {} complete'.format(m))
return m



async def slow_operation_2(n):
await asyncio.sleep(n)
print('Slow operation {} complete'.format(n))

return await slow_operation_1(m=n+1)

result = asyncio_run(slow_operation_2(2))

print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

In [6]: a = {'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]}

In [7]: for i in a.values():
...: for j in i:
...: print(j)
...:
4
5
6
7
8
9
1
2
3

更优雅的方式
In [8]: from itertools import chain

In [9]: for i in chain.from_iterable(a.values()):
...: print(i)
...:
4
5
6
7
8
9
1
2
3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15



def shutdown(signum, frame):
"""
Shutdown is called if the process receives a TERM signal. This way
we try to prevent an ugly stacktrace being rendered to the user on
a normal shutdown.
"""
logging.info("Shutting down")
sys.exit(0)


signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)