С помощью библиотеки asyncio и aiohttp
import asyncio
import aiohttp
sem = asyncio.Semaphore(10)
url = 'https://www.yandex.ru/'
async def request_get(client, url, limit):
while True:
try:
with(await limit):
async with client.get(url) as r:
print(r.status)
return await r.text()
except aiohttp.client_exceptions.ServerDisconnectedError:
print()
async def request_post(client, line, limit):
data = {'something': line}
while True:
try:
with(await limit):
async with client.get(url) as r:
print(r.status)
return await r.text()
except aiohttp.client_exceptions.ServerDisconnectedError:
print()
async def start(lines):
"""
Создет группу сопрограмм и ожидает их завершения
"""
# создаем экземпляр клиента
async with aiohttp.ClientSession() as client:
# создаем корутины
coroutines = [just(client, line) for line in lines]
completed, pending = await asyncio.wait(coroutines)
for item in completed:
item.result()
def parse_lines():
file = open('file.txt')
lines = file.readlines()
return lines
#Основной метод
async def just(clien, line):
line = line.strip()
data = {'something': line}
get = await request_get(clien, url, sem)
post = await request_post(clien, line, sem)
print(line+' - done.')
output = open(line + '.txt', 'w', encoding='utf-8')
output.write(post)
output.close()
if __name__ == "__main__":
lines = parse_lines()
event_loop = asyncio.get_event_loop()
try:
# запуск цикла обработки событий
event_loop.run_until_complete(start(lines))
finally:
# обязательно закрываем
event_loop.close()
Огромная просьба, напишите количество line, и время выполнения вашего и двух моих ответов, ради сравнения