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

观察并发 I/O、任务取消和进程计算

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。async_batch.py
async_batch.py123 行
"""Compare concurrent HTTP waits, local file I/O and a process pool."""
import argparse
import asyncio
from concurrent.futures import ProcessPoolExecutor
import json
from math import isqrt
from pathlib import Path
import os
from time import perf_counter
from urllib.parse import urlsplit

import aiofiles
import aiohttp


async def fetch(session,origin,route,gate):
    async with gate:
        try:
            async with session.post(origin+route,json={"batches":2},allow_redirects=False) as response:
                if response.status!=200:
                    return {"route":route,"code":"HTTP","http":response.status}
                data=await response.json()
                if not isinstance(data,dict) or type(data.get("units")) is not int:
                    return {"route":route,"code":"SCHEMA"}
                return {"route":route,"units":data["units"]}
        except TimeoutError:
            return {"route":route,"code":"TIMEOUT"}
        except (aiohttp.ClientError,ValueError):
            return {"route":route,"code":"TRANSPORT_OR_DATA"}


async def http_batch(origin,routes,workers,serial,timeout):
    parts=urlsplit(origin)
    if parts.scheme!="http" or parts.hostname!="127.0.0.1" or not parts.port or parts.username or parts.password or parts.path or parts.query or parts.fragment:
        raise ValueError("expected an explicit loopback HTTP origin")
    allowed={"/estimate","/count","/labels","/failed","/bad","/slow"}
    if any(route not in allowed for route in routes):
        raise ValueError("unknown fixture route")
    gate=asyncio.Semaphore(workers)
    started=perf_counter()
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout),trust_env=False) as session:
        if serial:
            values=[await fetch(session,origin,route,gate) for route in routes]
        else:
            values=await asyncio.gather(*(fetch(session,origin,route,gate) for route in routes))
    return {"results":values,"seconds":perf_counter()-started}


async def read_one(path):
    try:
        async with aiofiles.open(path,mode="r",encoding="utf-8") as handle:
            text=await handle.read()
        return {"file":path.name,"chars":len(text),"lines":len(text.splitlines())}
    except FileNotFoundError:
        return {"file":path.name,"code":"MISSING"}
    except (OSError,UnicodeError):
        return {"file":path.name,"code":"READ_ERROR"}


async def read_batch(paths):
    return await asyncio.gather(*(read_one(path) for path in paths))


async def deadline_demo():
    cancelled=[]
    completed=[]
    async def job(name,delay):
        try:
            await asyncio.sleep(delay)
            completed.append(name)
            return name
        except asyncio.CancelledError:
            cancelled.append(name)
            raise
    async def bounded(name,delay):
        try:
            return {"name":name,"result":await asyncio.wait_for(job(name,delay),timeout=.12)}
        except TimeoutError:
            return {"name":name,"code":"TIMEOUT"}
    results=await asyncio.gather(bounded("quick",.025),bounded("slow",.4))
    return {"results":results,"cancelled":cancelled,"completed":completed}


def primes(limit):
    found=sum(all(value%divisor for divisor in range(2,isqrt(value)+1)) for value in range(2,limit))
    return {"limit":limit,"count":found,"pid":os.getpid()}


def cpu_work(limits):
    with ProcessPoolExecutor(max_workers=2) as pool:
        return {"parent":os.getpid(),"items":list(pool.map(primes,limits))}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    commands=parser.add_subparsers(dest="kind",required=True)
    http=commands.add_parser("http")
    http.add_argument("origin")
    http.add_argument("routes",nargs="+")
    http.add_argument("--workers",type=int,default=3)
    http.add_argument("--timeout",type=float,default=2)
    http.add_argument("--serial",action="store_true")
    files=commands.add_parser("files")
    files.add_argument("paths",nargs="+",type=Path)
    commands.add_parser("deadlines")
    commands.add_parser("primes")
    args=parser.parse_args()
    if args.kind=="http":
        if args.workers<1 or args.timeout<=0:
            parser.error("positive workers and timeout are required")
        result=asyncio.run(http_batch(args.origin,args.routes,args.workers,args.serial,args.timeout))
    elif args.kind=="files":
        result=asyncio.run(read_batch(args.paths))
    elif args.kind=="deadlines":
        result=asyncio.run(deadline_demo())
    else:
        result=cpu_work((1000,2000))
    print(json.dumps(result,ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

入口文件:projects/skills-async/async_batch.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 async_batch.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Skills(技能)

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

下载课程关联工程包:Skills(技能)

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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