我需要在不同的服务器上不断向大约 150 个 API 发出许多请求。我跟交易工作,时间很关键,我不能浪费1毫秒。
我发现的解决方案和问题是:
也许是使用所有这些的解决方案。
如果 Python 中没有真正好的解决方案,我应该用什么来代替?
# Using Asyncio
import asyncio
import requests
async def main():
loop = asyncio.get_event_loop()
future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
response1 = await future1
response2 = await future2
print(response1.text)
print(response2.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# Using Threads
from threading import Thread
def do_api(url):
#...
#...
#...
#...
for i in range(50):
t = Thread(target=do_apis, args=(url_api[i],))
t.start()
Run Code Online (Sandbox Code Playgroud) 我目前在关闭应用程序的CTRL-C期间关闭asyncio协同程序时遇到问题.以下代码是我现在所拥有的精简版:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import asyncio
import time
import functools
import signal
class DummyProtocol(asyncio.Protocol):
def __init__(self, *args, **kwargs):
self._shutdown = asyncio.Event()
self._response = asyncio.Queue(maxsize=1)
super().__init__(*args, **kwargs)
def connection_made(self, transport):
self.transport = transport
def close(self):
print("Closing protocol")
self._shutdown.set()
def data_received(self, data):
#data = b'OK MPD '
# Start listening for commands after a successful handshake
if data.startswith(b'OK MPD '):
print("Ready for sending commands")
self._proxy_task = asyncio.ensure_future(self._send_commands())
return
# saving response for later consumption in self._send_commands
self._response.put_nowait(data)
async …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Asyncio和aiohttp库发出一堆请求(~1000),但我遇到了一个我找不到太多信息的问题.
当我用10个网址运行这个代码时,它运行得很好.当我用100多个网址运行它时,它会中断并给我RuntimeError: Event loop is closed错误.
import asyncio
import aiohttp
@asyncio.coroutine
def get_status(url):
code = '000'
try:
res = yield from asyncio.wait_for(aiohttp.request('GET', url), 4)
code = res.status
res.close()
except Exception as e:
print(e)
print(code)
if __name__ == "__main__":
urls = ['https://google.com/'] * 100
coros = [asyncio.Task(get_status(url)) for url in urls]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(coros))
loop.close()
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪可以在这里找到.
任何帮助或洞察都会非常感激,因为我现在已经敲了几个小时.显然,这表明事件循环已经关闭,应该仍然是开放的,但我不知道这是怎么可能的.
我想asyncio与tkinterGUI 结合使用.我是新手asyncio,我对它的理解不是很详细.单击第一个按钮时,此示例启动10个任务.任务只是模拟工作sleep()几秒钟.
Python的示例代码运行良好3.6.4rc1.但问题是GUI被冻结了.当我按下第一个按钮并启动10个asyncio任务时,我无法按下GUI中的第二个按钮,直到完成所有任务.GUI永远不应该冻结 - 这是我的目标.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import messagebox
import asyncio
import random
def do_freezed():
""" Button-Event-Handler to see if a button on GUI works. """
messagebox.showinfo(message='Tkinter is reacting.')
def do_tasks():
""" Button-Event-Handler starting the asyncio part. """
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(do_urls())
finally:
loop.close()
async def one_url(url):
""" One task. """
sec = random.randint(1, 15)
await …Run Code Online (Sandbox Code Playgroud) 下面是一个收集 URL 长度的简单程序。
import aiohttp
import asyncio
from time import perf_counter
URLS = ['http://www.cnn.com', 'http://www.huffpost.com', 'http://europe.wsj.com',
'http://www.bbc.co.uk', 'http://failfailfail.com']
async def async_load_url(url, session):
try:
async with session.get(url) as resp:
content = await resp.read()
print(f"{url!r} is {len(content)} bytes")
except IOError:
print(f"failed to load {url}")
async def main():
async with aiohttp.ClientSession() as session:
tasks = [async_load_url(url, session) for url in URLS]
await asyncio.wait(tasks)
if __name__ == "__main__":
start = perf_counter()
asyncio.run(main())
elapsed = perf_counter() - start
print(f"\nTook {elapsed} seconds")
Run Code Online (Sandbox Code Playgroud)
为什么以下代码在 python 3.9 中失败并出现运行时错误并忽略异常?如何修复它? …
大家好,我在尝试理解asyncio和aiohttp并使两者正常工作方面遇到困难。不仅我不正确地了解自己在做什么,这时我遇到了一个我不知道如何解决的问题。
我正在使用Windows 10 64位最新更新。
以下代码使用asyncio返回了标题中Content-Type中不包含html的页面列表。
import asyncio
import aiohttp
MAXitems = 30
async def getHeaders(url, session, sema):
async with session:
async with sema:
try:
async with session.head(url) as response:
try:
if "html" in response.headers["Content-Type"]:
return url, True
else:
return url, False
except:
return url, False
except:
return url, False
def checkUrlsWithoutHtml(listOfUrls):
headersWithoutHtml = set()
while(len(listOfUrls) != 0):
blockurls = []
print(len(listOfUrls))
items = 0
for num in range(0, len(listOfUrls)):
if num < MAXitems:
blockurls.append(listOfUrls[num - items])
listOfUrls.remove(listOfUrls[num - items])
items …Run Code Online (Sandbox Code Playgroud) import robloxapi, asyncio
client = robloxapi.Client(".ROBLOSECURITY Cookie Here") # Removed this for security reasons
async def main():
user = await client.get_self()
try:
role = await user.get_role_in_group(1)
except robloxapi.utils.errors.NotFound:
role = None
if role:
print(role.name)
else:
print("Not in group")
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
这段代码正在引发RuntimeError: Event loop is closed,我不知道为什么,
我尝试用这个替换 asyncio.run
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Run Code Online (Sandbox Code Playgroud)
但它给了我同样的错误
python ×6
aiohttp ×3
python-3.x ×3
async-await ×1
asynchronous ×1
concurrency ×1
event-loop ×1
request ×1
roblox ×1
tkinter ×1