在异步事件循环中运行 .render()(来自 requests_html)时,我收到错误“此事件循环已在运行”
Posted
技术标签:
【中文标题】在异步事件循环中运行 .render()(来自 requests_html)时,我收到错误“此事件循环已在运行”【英文标题】:When running .render() (from requests_html) in an asyncio event loop, I get the error 'This event loop is already running' 【发布时间】:2019-02-09 13:38:45 【问题描述】:我正在使用 discord.py 构建一个 Discord 机器人,它从 ESPN 获取实时足球比分。到目前为止我所拥有的是:
bot.py:
import discord, asyncio
from Scores import GetScores
client = discord.Client()
@client.event
async def on_message(message):
if message.content.startswith("!scores"):
Output = GetScores(message.content)
# rest of code
Scores.py:
from requests_html import HTMLSession
def GetScores(Message):
Link = "http://www.espn.co.uk/football/scoreboard"
Session = HTMLSession()
Response = Session.get(Link)
Response.html.render()
# rest of code
因此,当在 Discord 中发送“!scores”命令时,Bot.py 将运行事件循环并从 Scores.py 中调用“GetScores”函数。
问题是,当Response.html.render()
运行时,它给了我“此事件循环已在运行”错误。从那时起完全错误:
Response.html.render()
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\requests_html.py", line 572, in render
self.session.browser # Automatycally create a event loop and browser
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\requests_html.py", line 680, in browser
self._browser = self.loop.run_until_complete(pyppeteer.launch(headless=True, args=['--no-sandbox']))
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py", line 454, in run_until_complete
self.run_forever()
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py", line 408, in run_forever
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
来自this GitHub issue 我发现代码并非设计为在现有事件循环中运行。但是,我想知道 asyncio 中是否有解决方法允许它在这种情况下运行。我更希望找到一个解决方法而不是另一个解决方案/模块,因为我在 Discord 事件循环中测试它之前使用这个方法编写了整个东西,并发现它不起作用。
任何帮助将不胜感激,谢谢!
【问题讨论】:
【参考方案1】:使用render
的异步版本(称为arender
)应该适用于这种情况。
【讨论】:
以上是关于在异步事件循环中运行 .render()(来自 requests_html)时,我收到错误“此事件循环已在运行”的主要内容,如果未能解决你的问题,请参考以下文章