蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHONWindows CPython 3.12, real loopback HTTP/streams, isolated subprocess and asyncio synchronizationpython-asyncio.py
python-asyncio.py423 行
"""Bounded asyncio exercises using only local processes and loopback connections."""
import argparse
import asyncio
from contextvars import ContextVar, copy_context
import inspect
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
from urllib.request import ProxyHandler, build_opener


class Checks:
    def __init__(self):
        self.records = []

    def add(self, name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        self.records.append(dict(name=name, actual=actual, expected=expected, inputs=inputs,
                                 operation=operation, passed=True))


async def task_basics(check):
    states = []

    async def compute():
        states.append('entered')
        return 8

    pending = compute()
    before = [inspect.iscoroutine(pending), list(states), hasattr(asyncio,'coroutine')]
    value = await pending
    check('native coroutine starts only when awaited', [before, states, value],
          [[True, [], sys.version_info < (3,11)], ['entered'], 8], 'async def compute',
          'Inspect coroutine object and state before and after awaiting it')

    loop = asyncio.get_running_loop()
    future = loop.create_future()
    before = future.done()
    loop.call_soon(future.set_result,'released')
    check('Future completes through explicit callback',[before,await future,future.done()],
          [False,'released',True],'pending Future with a scheduled producer','Await a Future that receives a value')

    label = ContextVar('label',default='default')
    context = copy_context()
    context.run(label.set,'dispatch')

    async def task_value():
        return [asyncio.current_task().get_name(),label.get()]

    task = asyncio.create_task(task_value(),name='loader',context=context)
    before = task in asyncio.all_tasks()
    result = await task
    check('create_task name and context',result,['loader','dispatch'],'explicit task name and context',
          'Read name and ContextVar from the started task')
    check('current_task and all_tasks show live task',
          [before,task in asyncio.all_tasks(),asyncio.current_task() in asyncio.all_tasks()],
          [True,False,True],'one current task and one child','Compare live task listings before and after completion')

    order = []
    loop.call_soon(order.append,'callback')
    output = await asyncio.sleep(0,result='resumed')
    check('sleep yields and returns value',[order,output],[['callback'],'resumed'],
          'queued callback and sleep(0)','Yield to the event loop and collect a result')

    gate = asyncio.Event()
    cleaned = asyncio.Event()

    async def wait_clean():
        try:
            await gate.wait()
        finally:
            cleaned.set()

    started = asyncio.create_task(wait_clean())
    await asyncio.sleep(0)
    try:
        started.result()
    except asyncio.InvalidStateError:
        pending_error = True
    else:
        pending_error = False
    normal = [task.done(),task.result()]
    check('task result and done states',[started.done(),pending_error,normal],[False,True,[True,['loader','dispatch']]],
          'an unfinished task and a completed task','Read status and request result in both states')
    requested = started.cancel()
    try:
        await started
    except asyncio.CancelledError:
        cancelled = True
    else:
        cancelled = False
    check('cancellation delivers exception and cleanup',[requested,cancelled,cleaned.is_set(),started.done()],
          [True,True,True,True],'cancel a started task at Event.wait','Observe CancelledError and run finally')

    cleaned.clear()
    try:
        await asyncio.wait_for(wait_clean(),.01)
    except TimeoutError:
        timed_out = True
    else:
        timed_out = False
    check('wait_for cancels target and runs cleanup',[timed_out,cleaned.is_set(),asyncio.TimeoutError is TimeoutError],
          [True,True,True],'unsignaled Event with bounded deadline','Await timeout, check cleanup and the 3.12 exception alias')

    inner = asyncio.create_task(gate.wait())

    async def outer():
        return await asyncio.shield(inner)

    wrapper = asyncio.create_task(outer())
    await asyncio.sleep(0)
    wrapper.cancel()
    try:
        await wrapper
    except asyncio.CancelledError:
        shielded = not inner.done()
    else:
        shielded = False
    gate.set()
    check('shield keeps inner task alive',[shielded,await inner],[True,True],
          'shielded inner and cancelled outer task','Observe outer cancellation, then complete and await inner')


async def waiting_modes(check):
    release = asyncio.Event()

    async def fail():
        raise ValueError('synthetic')

    delayed = asyncio.create_task(release.wait())
    try:
        done,pending = await asyncio.wait([delayed],timeout=0)
        check('wait timeout leaves tasks pending',[len(done),delayed in pending,delayed.cancelled()],
              [0,True,False],'unsignaled task with timeout=0','Inspect sets without cancelling the pending task')
        quick = asyncio.create_task(asyncio.sleep(0,result=4))
        done,pending = await asyncio.wait([quick,delayed],return_when=asyncio.FIRST_COMPLETED)
        first = [quick in done,delayed in pending]
        failed = asyncio.create_task(fail())
        done,pending = await asyncio.wait([failed,delayed],return_when=asyncio.FIRST_EXCEPTION)
        first_error = [isinstance(failed.exception(),ValueError),delayed in pending]
        direct = asyncio.sleep(0)
        try:
            await asyncio.wait([direct])
        except TypeError:
            refused = True
        else:
            refused = False
        finally:
            direct.close()
        release.set()
        done,pending = await asyncio.wait([delayed,quick],return_when=asyncio.ALL_COMPLETED)
        check('wait rejects coroutine and supports three modes',
              [refused,first,first_error,len(done),len(pending)],[True,[True,True],[True,True],2,0],
              'one delayed, one completed and one failed task plus a bare coroutine','Compare all wait predicates and validate 3.12 inputs')
    finally:
        release.set()
        await delayed

    release.clear()
    sibling = asyncio.create_task(release.wait())
    try:
        await asyncio.gather(fail(),sibling)
    except ValueError:
        error_seen = True
    else:
        error_seen = False
    survived = not sibling.done()
    release.set()
    await sibling
    results = await asyncio.gather(asyncio.sleep(0,result=7),fail(),return_exceptions=True)
    check('gather raises or collects exceptions',[error_seen,survived,results[0],type(results[1]).__name__],
          [True,True,7,'ValueError'],'one failing coroutine and one continuing sibling','Compare default propagation with return_exceptions=True')


async def synchronization(check):
    lock = asyncio.Lock()
    stock = 0

    async def add_stock():
        nonlocal stock
        async with lock:
            before = stock
            await asyncio.sleep(0)
            stock = before+1

    await asyncio.gather(*(add_stock() for _ in range(6)))
    check('async Lock preserves shared updates',stock,6,'six tasks with a forced scheduling point',
          'Hold the lock across reading, yielding and writing')

    signal = asyncio.Event()
    waiter = asyncio.create_task(signal.wait())
    await asyncio.sleep(0)
    suspended = not waiter.done()
    signal.set()
    awakened = await waiter
    signal.clear()
    check('async Event wakes and clears',[suspended,awakened,signal.is_set()],[True,True,False],
          'one waiter and an unset event','Suspend, signal and clear the event')

    work = asyncio.Queue(maxsize=1)
    stop = object()
    await work.put(2)
    next_item = asyncio.create_task(work.put(5))
    await asyncio.sleep(0)
    delayed = not next_item.done()
    results = []

    async def consume():
        while True:
            item = await work.get()
            try:
                if item is stop:
                    return
                results.append(item)
            finally:
                work.task_done()

    consumer = asyncio.create_task(consume())
    await next_item
    await work.put(stop)
    await work.join()
    await consumer
    check('async Queue accounts for data and stop token',[delayed,results,consumer.done()],
          [True,[2,5],True],'capacity one, two values and a stop token','Observe a blocked put, account for items and stop')

    limiter = asyncio.Semaphore(2)
    gate = asyncio.Event()
    two_inside = asyncio.Event()
    active = maximum = 0

    async def enter():
        nonlocal active,maximum
        async with limiter:
            active += 1
            maximum = max(maximum,active)
            if active==2:
                two_inside.set()
            await gate.wait()
            active -= 1

    tasks = [asyncio.create_task(enter()) for _ in range(4)]
    await two_inside.wait()
    blocked = sum(task.done() for task in tasks)
    gate.set()
    await asyncio.gather(*tasks)
    check('async Semaphore bounds concurrency',[blocked,maximum,active],[0,2,0],
          'four entrants, two permits','Hold the first entrants, then release and inspect the maximum')


async def local_http(check, aiohttp_enabled):
    arrivals = []
    both = asyncio.Event()
    first_sent = asyncio.Event()
    active = set()

    async def serve(reader, writer):
        task = asyncio.current_task()
        active.add(task)
        try:
            header = await reader.readuntil(b'\r\n\r\n')
            path = header.split(b' ')[1].decode('ascii')
            arrivals.append(path)
            if path=='/fast':
                both.set()
                await first_sent.wait()
            if path=='/slow':
                await both.wait()
            body = ('reply '+path).encode('ascii')
            writer.write(b'HTTP/1.1 200 OK\r\nContent-Length: '+str(len(body)).encode('ascii')
                         +b'\r\nConnection: close\r\n\r\n'+body)
            await writer.drain()
        finally:
            writer.close()
            await writer.wait_closed()
            active.discard(task)

    async with await asyncio.start_server(serve,'127.0.0.1',0) as server:
        port = server.sockets[0].getsockname()[1]

        def sync_reads():
            opener = build_opener(ProxyHandler({}))
            answers = []
            for path in ('/serial-a','/serial-b'):
                with opener.open(f'http://127.0.0.1:{port}{path}',timeout=3) as response:
                    answers.append(response.read().decode('ascii'))
            return answers

        serial = await asyncio.to_thread(sync_reads)
        check('blocking HTTP client reads serially',[arrivals[:],serial],
              [['/serial-a','/serial-b'],['reply /serial-a','reply /serial-b']],
              ['/serial-a','/serial-b'],'Read each real local HTTP response before sending the next request')
        arrivals.clear()
        finished = []

        async def request(path):
            reader,writer = await asyncio.open_connection('127.0.0.1',port)
            try:
                writer.write(f'GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n'.encode('ascii'))
                await writer.drain()
                head = await reader.readuntil(b'\r\n\r\n')
                body = (await reader.read()).decode('ascii')
                finished.append(path)
                if path=='/slow':
                    first_sent.set()
                return [head.split(b'\r\n',1)[0].decode('ascii'),body]
            finally:
                writer.close()
                await writer.wait_closed()

        tasks = [asyncio.create_task(request(p)) for p in ('/fast','/slow')]
        results = await asyncio.gather(*tasks)
        check('local HTTP overlaps while results retain input order',[sorted(arrivals),finished,results],
              [['/fast','/slow'],['/slow','/fast'],[['HTTP/1.1 200 OK','reply /fast'],['HTTP/1.1 200 OK','reply /slow']]],
              ['/fast','/slow'],'Require both requests before releasing either response and enforce reversed completion')

        if aiohttp_enabled:
            import aiohttp

            async def fetch(session,path):
                async with session.get(f'http://127.0.0.1:{port}{path}') as response:
                    response.raise_for_status()
                    return [response.status,await response.text()]

            async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3),trust_env=False) as session:
                gathered = await asyncio.gather(fetch(session,'/session-a'),fetch(session,'/session-b'))
            check('aiohttp session fetches real local responses',[gathered,session.closed],
                  [[[200,'reply /session-a'],[200,'reply /session-b']],True],
                  ['/session-a','/session-b'],'Reuse one session, await real responses, then close it')

        if active:
            await asyncio.gather(*list(active))


async def services(check, aiohttp_enabled):
    await task_basics(check)
    await waiting_modes(check)
    await synchronization(check)
    await local_http(check,aiohttp_enabled)
    loop = asyncio.get_running_loop()
    main_thread = threading.get_ident()
    begun = asyncio.Event()
    proceed = threading.Event()

    def blocking(a, *, increment):
        loop.call_soon_threadsafe(begun.set)
        if not proceed.wait(4):
            raise RuntimeError('work was not released')
        return [a+increment,threading.get_ident()!=main_thread]

    background = asyncio.create_task(asyncio.to_thread(blocking,5,increment=2))
    await begun.wait()
    concurrent = not background.done()
    proceed.set()
    check('to_thread forwards args without blocking loop',[concurrent,await background],
          [True,[7,True]],'blocking synchronous callable with kwargs','Wait on the event loop while another thread waits on a signal')

    proc = await asyncio.create_subprocess_exec(sys.executable,'-I','-c','print(17*3)',
                                               stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
    stdout,stderr = await proc.communicate()
    check('async subprocess returns actual output',[stdout.decode().strip(),stderr.decode(),proc.returncode],
          ['51','',0],'current Python executable and fixed argument list','Collect actual subprocess streams and exit status')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--aiohttp',action='store_true')
    parser.add_argument('--local-aiohttp-site',type=Path)
    options = parser.parse_args()
    if options.local_aiohttp_site:
        sys.path.insert(0,str(options.local_aiohttp_site.resolve(strict=True)))
    aiohttp_enabled = options.aiohttp or bool(options.local_aiohttp_site)
    if aiohttp_enabled:
        import aiohttp  # Import before starting the event loop.
    check = Checks()
    holder = {}

    async def run_entry():
        holder['loop'] = asyncio.get_running_loop()
        await asyncio.wait_for(services(check.add,aiohttp_enabled),20)
        return holder['loop'].get_debug()

    debug = asyncio.run(run_entry(),debug=True)
    check.add('run debug flag and closes loop',[debug,holder['loop'].is_closed()],[True,True],
              'asyncio.run(debug=True)','Inspect the running flag and closed loop state')
    env = dict(os.environ, PYTHONASYNCIODEBUG='1')
    debug_probe = (
        "import asyncio\n"
        "async def probe():\n return asyncio.get_running_loop().get_debug()\n"
        "print(asyncio.run(probe(), debug=None))"
    )
    debug_child = subprocess.run([sys.executable,'-B','-s','-X','utf8','-c',debug_probe],
                                 env=env,capture_output=True,text=True,check=True,timeout=8)
    check.add('run debug None reads environment',[debug_child.stdout.strip(),debug_child.stderr],['True',''],
              'PYTHONASYNCIODEBUG=1 in a subprocess that reads environment variables','Use default debug selection')
    loop = asyncio.new_event_loop()
    try:
        future = loop.create_future()
        loop.call_soon(future.set_result,'ok')
        check.add('low-level loop completes future',loop.run_until_complete(future),'ok',
                  'Future completed by call_soon','Run until the scheduled result arrives')
        observed = []
        loop.call_soon(observed.append,'ready')

        def end(label):
            observed.append(label)
            loop.stop()

        loop.call_later(.01,end,'timer')
        loop.run_forever()
    finally:
        loop.close()
    check.add('low-level loop callbacks stop and close',[observed,loop.is_closed()],[['ready','timer'],True],
              'call_soon then call_later','Run callbacks, stop the loop and close it')
    print(json.dumps(check.records,ensure_ascii=False))


if __name__ == '__main__':
    main()
本例需在 Windows CPython 3.12, real loopback HTTP/streams, isolated subprocess and asyncio synchronization 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPython 3.12, real loopback HTTP/streams, isolated subprocess and asyncio synchronization

入口文件:projects/python-lab/python-asyncio.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-asyncio.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPython 3.12, real loopback HTTP/streams, isolated subprocess and asyncio synchronization。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a291.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习