Pythonコラボレーションとasyncioモジュール
単純な使用
async def文または@asyncio.coroutine装飾のジェネレータを使用してasyncioモジュールを使用できるコラボレーションを実現
ジェネレータベースのコパスは、元のyield構文ではなくyield fromを使用する必要があります.
import asyncio
@asyncio.coroutine
def hello():
print("Hello world!")
r = yield from asyncio.sleep(1) #asyncio.sleep(1) , 1 IO
print("Hello again!")
loop = asyncio.get_event_loop() #
loop.run_until_complete(hello()) # ,
loop.close() #
@asyncio.coroutine装飾器は1つのジェネレータ関数をコヒーレント関数としてマークします
yield fromはasyncio.sleep(1)コヒーレンスの完了を待つが、その間、メインスレッドは待たずにイベントループ内の他の実行可能なコヒーレンスを実行するため、同時実行を実現することができる.
Python 3.5に@asyncio.coroutineとyield fromを置き換えるための新しい構文async/awaitが追加されました
@asyncio.coroutine/yield fromとasync/awaitの2つの方法が混在していないことに注意してください
イベントループで複数のコパスを実行できます
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
Coroutine
, yield , async def @asyncio.coroutine , asyncio Coroutine
" " 。
async def @asyncio.coroutine , asyncio.iscoroutinefunction(func)
, asyncio.iscoroutine(obj)
return expression await yield from
raise expression
Future ,Task Future , , Future Task ,
Future ,
Future
result = await/yield from future , future , future ,
future (future.canael()), asyncio.CanceledError
loop.create_task() asyncio.ensure_future() loop.create_future() future
result = await asyncio.ensure_future(cor), coroutine future , , , future
Coroutine
,
result = await/yield from coroutine ,
future 。。。。。
ensure_future() create_task() future ,
future
async @asyncio.coroutine , , yield/ await/yield from future
future
, ,
await coroutine , future
future , future
, , time.sleep() , await
, , , run_inexecutor() concurrent.futures
Future ,Pending, running, done, cancelled
pending ,future future
running future ,running pending
future Task.current_task() None, future ,future (future.cancel() )
done ,
cancelled done
( loop.stop() ) (loop.call_soon() )
, ( KeyborderInterrupt ) future future ,
loop.stop() , ,
loop.stop() ,
stop() , , ,
await stop() , future , future , , stop() ( stop() future , , )
,
,
future await stop() , future , future , ,
loop.call_soon() , FIFO ,
asyncio
ascio , , IO
,
asyncio , ,
asyncio asyncio.TimeoutError,asyncio.InvlidStateError
asyncio.AbstractEventLoop
asyncio.BaseEventLoop , AbstractEventLoop , asyncio
, , , AbstractEventLoop
asyncio ,SelectorEventLoop PractorEventLoop
AbstractEventLoop
asyncio.SelectorEventLoop selectors IO/ ,
Windows ,, ,
asyncio.ProactorEventLoop
Windows , IO (IOCP)
, , ,
asyncio.get_event_loop() , AbstractEventLoop
asyncio.set_event_loop(loop) loop
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
asyncio.new_event_loop()
loop.run_forever() stop(), , 0, io
run_forever() stop(), ,
loop.stop() , run_forever()
loop.run_until_complete(future) Future , Future ,
loop.close()
, ,
,
loop.is_running()
loop.is_closed()
loop.create_future() Future python3.5.2
loop.create_task(coro) task, future
loop.call_soon(callback, *args) ,
,
,
functoolspartial()
loop.call_soon(functools.partial(print, "Hello", flush=True)) # print("Hello", flush=True).
Future
future , ,
Future
asyncio.Future(*,loop=None) Future
future.cancel() future,
future.cancelled() future , True
future.done() future , True
, future
future.result( ) future , future , CancelledError, future , InvalidStateError, ft ,
future.exception( ) future , future , , , None, CancelledError, , InvalidStateError
future.set_result(result) future , future , InvlidStateError
future.set_exception(exception) future , , InvildStateError
future.add_done_callback(fn) future , ft ,
future.remove_done_callback(fn) ,
Task
asyncio.Task(coro, * ,loop=None)
Task Future , coro future
Task , asyncio.ensure_future() loop.create_task()
Task.all_tasks(loop=None)
,
Task.current_task(loop=None)
task.cancel()
CanceledError , try/except/finalyy
future.cancel , , ,
,cancelled() True, CancelledError ,
Task
asyncio.as_completed(fs, *, loop=None, timeout=None)
, fs (done ) Future
timeout future , TimeoutError
asyncio.ensure_future(coro_or_future, * , loop=None)
, Future, task , Future,
loop None
create_task()
asyncio.async(coro_or_future, *, loop=None) ensure_future() python3.4.4
asyncio.gather(*coros_or_futures, loop=None,return_exception=False)
futures future
future , future ( , futures )
return_exception True, ,
, future
future ,
CancelledError, future ,
asyncio.iscoroutine(obj)
obj , True
asyncio.iscoroutinefunction(func)
func , True
asyncio.shidle(arg,*, loop=None)
future,
res = from shield(something1())
res = yield from something2()
, , something2 CancelError, something() , , , await CancelledError
something1() , , try/except
asycnio.sleep(delay, result=None, *, loop=None)
( ) , result ,
asyncio.wait(futures,*, loop=None, timeout=None,return_when=ALL_COMPLETED)
futures future , task
Future (done,pending)
done future,pending , future
futures ,timeout , None,
return_when
FIRST_COMPLETED ,
FIRST_EXCEPTION future , , future , ALL_COMPLETED
ALL_COMPLETED future ,
asyncio.wait_for(fut,timeout, *, loop=None)
Future , None, future
task
, , TimeoutError, shield()
,future