pythonでのasyncioの使用例


Python 3は、asyncioモジュールおよびawaitおよびasyncキーワードを介して非同期I/Oをサポートします.
ステッププログラミングは、通常、実行時間および順序が不確定であるため、フック関数(コールバック関数)またはFutureオブジェクトによってタスク実行の結果を取得する必要があるマルチタスクコラボレーション処理によって実現される.
import asyncio

async def fetch(host):
    #          
    print(f'    {host}')
    #         
    reader, writer = await asyncio.open_connection(host, 80)
    #          
    writer.write(b'GET / HTTP/1.1\r
') writer.write(f'Host:{host}\r
'.encode()) writer.write(b'\r
') # await writer.drain() # line = await reader.readline() while line != b'\r
': print(line.decode().rsplit()) line = await reader.readline() print('
') writer.close() def main(): urls = ('www.baidu.com', 'www.csdn.net', 'www.163.com') # loop = asyncio.get_event_loop() # , tasks = [fetch(url) for url in urls] # wait: Task(Future) # run_until_complete: , Future loop.run_until_complete(asyncio.wait(tasks)) loop.close() if __name__ == '__main__': main()

実行結果:
www.163を捕まえる.comはwww.baiduを捕まえ始めた.comはwww.csdnのキャプチャを開始する.net ['HTTP/1.1', '200', 'OK'] ['Date:', 'Tue,', '31', 'Mar', '2020', '15:08:46', 'GMT'] ['Content-Type:', 'text/html;', 'charset=GBK'] ['Transfer-Encoding:', 'chunked'] ['Connection:', 'keep-alive'] ['Expires:', 'Tue,', '31', 'Mar', '2020', '15:09:59', 'GMT'] ['Server:', 'nginx'] ['Cache-Control:', 'no-cache,no-store,private'] ['Age:', '7'] ['Vary:', 'Accept-Encoding'] ['X-Ser:', 'BC80_dx-lt-yd-jiangsu-taizhou-4-cache-4,', 'BC84_dx-lt-yd-jiangsu-taizhou-4-cache-4,', 'BC233_ck-hubei-wuhan-2-cache-2,', 'BC196_ck-hubei-wuhan-2-cache-1'] ['cdn-user-ip:', '49.211.105.136'] ['cdn-ip:', '124.203.225.195'] ['X-Cache-Remote:', 'HIT'] ['cdn-source:', 'baishan']
['HTTP/1.1', '200', 'OK'] ['Accept-Ranges:', 'bytes'] ['Cache-Control:', 'no-cache'] ['Connection:', 'keep-alive'] ['Content-Length:', '14615'] ['Content-Type:', 'text/html'] ['Date:', 'Tue,', '31', 'Mar', '2020', '15:08:46', 'GMT'] ['P3p:', 'CP="', 'OTI', 'DSP', 'COR', 'IVA', 'OUR', 'IND', 'COM', '"'] ['P3p:', 'CP="', 'OTI', 'DSP', 'COR', 'IVA', 'OUR', 'IND', 'COM', '"'] ['Pragma:', 'no-cache'] ['Server:', 'BWS/1.1'] ['Set-Cookie:', 'BAIDUID=9086941EE74E01736F33F9B8CF3844A2:FG=1;', 'expires=Thu,', '31-Dec-37', '23:55:55', 'GMT;', 'max-age=2147483647;', 'path=/;', 'domain=.baidu.com'] ['Set-Cookie:', 'BIDUPSID=9086941EE74E01736F33F9B8CF3844A2;', 'expires=Thu,', '31-Dec-37', '23:55:55', 'GMT;', 'max-age=2147483647;', 'path=/;', 'domain=.baidu.com'] ['Set-Cookie:', 'PSTM=1585667326;', 'expires=Thu,', '31-Dec-37', '23:55:55', 'GMT;', 'max-age=2147483647;', 'path=/;', 'domain=.baidu.com'] ['Set-Cookie:', 'BAIDUID=9086941EE74E01739D5D416533CDA255:FG=1;', 'max-age=31536000;', 'expires=Wed,', '31-Mar-21', '15:08:46', 'GMT;', 'domain=.baidu.com;', 'path=/;', 'version=1;', 'comment=bd'] ['Traceid:', '1585667326274850689010390091619431081419'] ['Vary:', 'Accept-Encoding'] ['X-Ua-Compatible:', 'IE=Edge,chrome=1']
['HTTP/1.1', '301', 'Moved', 'Permanently'] ['Server:', 'openresty'] ['Date:', 'Tue,', '31', 'Mar', '2020', '15:08:46', 'GMT'] ['Content-Type:', 'text/html'] ['Content-Length:', '182'] ['Connection:', 'keep-alive'] ['Keep-Alive:', 'timeout=20'] ['Location:', 'https://www.csdn.net/']
Process finished with exit code 0