====== 13 Python 非同期処理 asyncio ======
===== 1.非同期処理でURL取得 =====
asyncioでURLにアクセスし結果を取得、戻り値として受け取る。
ここで戻り地を受け取る。
戻り値の順番は、gatherの順番どおりに戻ってくる
results = loop.run_until_complete(gather)
import asyncio
import time
import functools
import requests
def sleep(sec):
time.sleep(sec)
return sec
async def get_global_ip():
loop = asyncio.get_event_loop()
resp = await loop.run_in_executor(None, requests.get, 'http://fl8.jp')
print('get_ip')
return resp.text
async def parallel_sleep(seconds):
loop = asyncio.get_event_loop()
resp = await loop.run_in_executor(None, sleep, seconds)
print(f'sleep {resp}sec')
return resp
def main():
loop = asyncio.get_event_loop()
gather = asyncio.gather(
parallel_sleep(10),
get_global_ip(),
parallel_sleep(1)
)
results = loop.run_until_complete(gather)
print(results)
if __name__ == '__main__':
main()
===== 実行結果 =====
$ python3.6 test2.ppy
get url
sleep 1sec
sleep 10sec
[10, 'fl8.jp
100.100.100.10 ', 1]
{{tag>python}}