- 已完成:logging模块的学习
- 接下来的目标:分为两步——要做什么和怎么做
- requests模块的学习
- python程序debug的方式
- 异步
- 网络的基本知识(做什么)
asnycio basic
https://pymotw.com/3/asyncio/index.html
app: <=interact=> event loop:
coroutines:
- special functions that give up control to the caller without losing their state
Q: a class-based abstraction layer for protocols and transports for writing code using callbacks instead of writing coroutines directly.
“coroutine”的两种含义:函数和对象
The function that defines a coroutine==a coroutine function (iscoroutinefunction() returns True).
The object obtained by calling a coroutine function==a coroutine object (iscoroutine() returns True).
Things a coroutine can do:
result = await future
orresult = yield from future
- suspends the coroutine until the future is done, then returns the future’s result, or raises an exception, which will be propagated. (If the future is cancelled, it will raise a CancelledError exception.)
- tasks ==futures
result = await coroutine
orresult = yield from coroutine
- wait for another coroutine to produce a result
- return expression
- raise exception
运行cotouring
- Call != start
- schedule its execution.
- await or yield from
- ensure_future() function or AbstractEventLoop.create_task() method.
import asyncio
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
Coroutines (and tasks) can only run when the event loop is running.
future:
a data structure representing the result of work that has not been completed yet.
Task:
a subclass of Future that knows how to wrap and manage the execution for a coroutine.
https://pymotw.com/3/asyncio/coroutines.html
coroutine function-> coroutine object
coroutine object .send()->run function code
- 建立一个coroutine func
- 建立event loop or 实例化一个特定的eventloop
run_until_complete():用asyncio来start一个协程 - 从coroutine建立新的coroutine await() context 转换?
- earlier Python 3 -> @asyncio + yield from
- now: async def + await
python
@asyncio.coroutine()
def func()
yield
Future
work not completed yet<-event loop watch for
- set_result(): change state
- await