【发布时间】:2018-11-07 23:06:20
【问题描述】:
不久前,我开始学习 asyncio。我遇到了一个问题。我的代码没有终止。我想不通。请帮帮我!
import signal
import sys
import asyncio
import aiohttp
import json
loop = asyncio.get_event_loop()
client = aiohttp.ClientSession(loop=loop)
async def get_json(client, url):
async with client.get(url) as response:
assert response.status == 200
return await response.read()
async def get_reddit_cont(subreddit, client):
data1 = await get_json(client, 'https://www.reddit.com/r/' + subreddit + '/top.json?sort=top&t=day&limit=50')
jn = json.loads(data1.decode('utf-8'))
print('DONE:', subreddit)
def signal_handler(signal, frame):
loop.stop()
client.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
for key in {'python':1, 'programming':2, 'compsci':3}:
asyncio.ensure_future(get_reddit_cont(key, client))
loop.run_forever()
结果:
DONE: compsci
DONE: programming
DONE: python
...
我试图完成一些事情,但结果并不稳定。
future = []
for key in {'python':1, 'programming':2, 'compsci':3}:
future=asyncio.ensure_future(get_reddit_cont(key, client))
loop.run_until_complete(future)
结果(1 个任务而不是 3 个):
DONE: compsci
[Finished in 1.5s]
我这样解决了我的问题:
添加者:
async with aiohttp.ClientSession () as a client:
在:
async def get_reddit_cont (subreddit, client):
还有:
if __name__ == '__main__':
loop = asyncio.get_event_loop()
futures = [get_reddit_cont(subreddit,client) for subreddit in range(1,6)]
result = loop.run_until_complete(asyncio.gather(*futures))
但是当代码完成后,我得到消息:
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x034021F0>
[Finished in 1.0s]
我不明白为什么会这样。
但是当我尝试执行“for key”大约 60 次或更多次时,我得到一个错误:
...
aiohttp.client_exceptions.ClientOSError: [WinError 10054] 远程主机强行终止现有连接
【问题讨论】:
标签: python python-asyncio