import threading
import asyncio
@asyncio.coroutine
def hello():
print('Start Hello', threading.currentThread())
yield from asyncio.sleep(5)
print('End Hello', threading.currentThread())
@asyncio.coroutine
def world():
print('Start World', threading.currentThread())
yield from asyncio.sleep(3)
print('End World', threading.currentThread())
# 获取EventLoop:
loop = asyncio.get_event_loop()
tasks = [hello(), world()]
# 执行coroutine
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
import asyncio
@asyncio.coroutine
def worker(text):
"""
协程运行的函数
:param text:
:return:
"""
i = 0
while True:
print(text, i)
try:
yield from asyncio.sleep(.1)
except asyncio.CancelledError:
break
i += 1
@asyncio.coroutine
def client(text, io_used):
worker_fu = asyncio.ensure_future(worker(text))
# 假装等待I/O一段时间
yield from asyncio.sleep(io_used)
# 结束运行协程
worker_fu.cancel()
return 'done'
loop = asyncio.get_event_loop()
tasks = [client('xiaozhe', 3), client('zzzz', 5)]
result = loop.run_until_complete(asyncio.wait(tasks))
loop.close()
print('Answer:', result)
cc_list = ['China', 'USA']
@asyncio.coroutine
def get_flag(cc):
url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
resp = yield from aiohttp.request('GET', url)
image = yield from resp.read()
return image
@asyncio.coroutine
def download_one(name):
image = yield from get_flag(name)
save_flag(image, name.lower() + '.gif')
return name
loop = asyncio.get_event_loop()
wait_coro = asyncio.wait([download_one(cc) for cc in sorted(cc_list)])
res, _ = loop.run_until_complete(wait_coro)
loop.close()
@asyncio.coroutine
def hello():
print("Hello world!")
r = yield from asyncio.sleep(1)
print("Hello again!")
async def hello():
print("Hello world!")
r = await asyncio.sleep(1)
print("Hello again!")
import asyncio
import aiohttp
urls = [
'http://www.163.com/',
'http://www.sina.com.cn/',
'https://www.hupu.com/',
'http://www.csdn.net/'
]
async def get_url_data(u):
"""
读取url的数据
:param u:
:return:
"""
print('running ', u)
async with aiohttp.ClientSession() as session:
async with session.get(u) as resp:
print(u, resp.status, type(resp.text()))
# print(await resp.text())
return resp.headers
async def request_url(u):
"""
主调度函数
:param u:
:return:
"""
res = await get_url_data(u)
return res
loop = asyncio.get_event_loop()
task_lists = asyncio.wait([request_url(u) for u in urls])
all_res, _ = loop.run_until_complete(task_lists)
loop.close()
print(all_res)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有