demo01
import asyncio
import time
async def play_game():
"""玩游戏"""
print('玩游戏')
await asyncio.sleep(1)
print("玩游戏...")
await asyncio.sleep(1)
print("玩游戏...")
await asyncio.sleep(3)
print('玩游戏')
return "游戏gg了"
async def dian_wai_mai():
"""点外卖"""
print("点外卖")
await asyncio.sleep(1)
print("等外卖...")
await asyncio.sleep(1)
print("等外卖...")
await asyncio.sleep(1)
print("外卖到")
return "外卖到了"
async def main():
print("start main")
future1 = dian_wai_mai()
future2 = play_game()
ret1, ret2 = await asyncio.gather(future1, future2)
print(ret1, ret2)
print("end main")
if __name__ == '__main__':
t1 = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
t2 = time.time()
print('cost:', t2-t1)
demo02
"""
# 真正的协程模块就是使用greenlet完成的切换
from greenlet import greenlet
def eat(name):
print('%s eat 1' % name) # 2
g2.switch('taibai') # 3
print('%s eat 2' % name) # 6
g2.switch() # 7
def play(name):
print('%s play 1' % name) # 4
g1.switch() # 5
print('%s play 2' % name) # 8
g1 = greenlet(eat)
g2 = greenlet(play)
g1.switch('taibai') # 可以在第一次switch时传入参数,以后都不需要 #1
"""
"""
import asyncio
async def func1():
print(1)
await asyncio.sleep(2)
print(2)
async def func2():
print(3)
await asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks)) """
"""
下载图片使用第三方模块aiohttp, 请提前安装: pip3 install aiohttp
"""
import aiohttp
import asyncio
import httpx
async def fetch(session, url):
print("发送请求:", url)
async with session.get(url, verify_ssl=False) as response:
content = await response.content.read()
file_name = url.rsplit('_')[-1]
with open(file_name, mode='wb') as file_object:
file_object.write(content)
async def main():
async with aiohttp.ClientSession() as session:
url_list = [
'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg',
'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
]
tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
await asyncio.wait(tasks)
async def fetch01(session, url):
print("发送请求:", url)
response = await session.get(url)
assert response.status_code == 200
content = response.content
file_name = url.rsplit('_')[-1]
with open(file_name, mode='wb') as file_object:
file_object.write(content)
async def main01():
async with httpx.AsyncClient() as session:
url_list = [
'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg',
'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
]
tasks = [asyncio.create_task(fetch01(session, url)) for url in url_list]
await asyncio.wait(tasks)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main01())