简体   繁体   English

“运行时错误:此事件循环已在运行”; 在 python 3.6.5 中调试 aiohttp、asyncio 和 IDE“spyder3”

[英]“RuntimeError: This event loop is already running”; debugging aiohttp, asyncio and IDE “spyder3” in python 3.6.5

I'm struggling to understand why I am getting the "RuntimeError: This event loop is already running" runtime error.我正在努力理解为什么我会收到“运行时错误:此事件循环已经在运行”运行时错误。 I have tried to run snippets of code from " https://aiohttp.readthedocs.io/en/stable/ " however, I keep getting the same issue.我曾尝试从“ https://aiohttp.readthedocs.io/en/stable/ ”运行代码片段,但是,我一直遇到同样的问题。

Code snippet from Tutorial:教程中的代码片段:


import aiohttp
import asyncio
import async_timeout

async def fetch(session, url):
    async with async_timeout.timeout(10):
        async with session.get(url) as response:
            return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://python.org')
        print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

RESULTS from tutorial snippet (while running code from spyder IDE):教程片段的结果(从 spyder IDE 运行代码时):


RuntimeError: This event loop is already running运行时错误:此事件循环已在运行

<!doctype html>"

... (more html) ...(更多 html)


Personal code snippet (not from the tutorial referenced above):个人代码片段(不是来自上面引用的教程):


import aiohttp
import asyncio
import time

urls = ['https://api.robinhood.com/quotes/c4f6720a-0364-4e7b-8c41-705696759e1a/']

async def fetch(client, url):
    async with client.request('get', url) as response:
        if response.status == 200:
            data = await response.text()
        else:
            data = []
        print(data)
        return(data)

async def get_async_urls(urls):
    async with aiohttp.ClientSession() as client:
        return await asyncio.gather(*(fetch(client, url) for url in urls))

if __name__ == '__main__':
    t0 = time.time()
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(get_async_urls(urls))
    print(results)
    t1 = time.time()
    total_time = t1-t0
    loop.close()

RESULTS from personal snippet (while running code from spyder IDE):来自个人片段的结果(从 spyder IDE 运行代码时):


RuntimeError: This event loop is already running运行时错误:此事件循环已在运行

{"ask_price":"14.9000","ask_size":100,"bid_price":"14.0100","bid_size":100,"last_trade_price":"14.7900","last_extended_hours_trade_price":"14.7900","previous_close":"14.3600","adjusted_previous_close":"14.3600","previous_close_date":"2018-05-07","symbol":"SURF","trading_halted":false,"has_traded":true,"last_trade_price_source":"consolidated","updated_at":"2018-05-08T20:01:21Z","instrument":" https://api.robinhood.com/instruments/43d56335-f2f6-4711-b650-55be2396f814/ "} {"ask_price":"14.9000","ask_size":100,"bid_price":"14.0100","bid_size":100,"last_trade_price":"14.7900","last_extended_hours_trade_price"vious:"14.7900","关闭前" 14.3600","adjusted_previous_close":"14.3600","previous_close_date":"2018-05-07","symbol":"SURF","trading_halted":false,"has_traded":true,"last_trade_price_source":"合并" ,"updated_at":"2018-05-08T20:01:21Z","instrument":" https://api.robinhood.com/instruments/43d56335-f2f6-4711-b650-55be2396f814/ "}


RESULTS from personal snippet (while running from cmd "python personal_snippet.py"):来自个人片段的结果(从 cmd“pythonpersonal_snippet.py”运行时):


{"ask_price":"14.9000","ask_size":100,"bid_price":"14.0100","bid_size":100,"last_trade_price":"14.7900","last_extended_hours_trade_price":"14.7900","previous_close":"14.3600","adjusted_previous_close":"14.3600","previous_close_date":"2018-05-07","symbol":"SURF","trading_halted":false,"has_traded":true,"last_trade_price_source":"consolidated","updated_at":"2018-05-08T20:01:21Z","instrument":" https://api.robinhood.com/instruments/43d56335-f2f6-4711-b650-55be2396f814/ "} ['{"ask_price":"14.9000","ask_size":100,"bid_price":"14.0100","bid_size":100,"last_trade_price":"14.7900","last_extended_hours_trade_price":"14.7900","previous_close":"14.3600","adjusted_previous_close":"14.3600","previous_close_date":"2018-05-07","symbol":"SURF","trading_halted":false,"has_traded":true,"last_trade_price_source":"consolidated","updated_at":"2018-05-08T20:01:21Z","instrument":" https://api.robinhood.com/instruments/43d56335-f2f6-4711-b650-55be2396f814/ "}'] {"ask_price":"14.9000","ask_size":100,"bid_price":"14.0100","bid_size":100,"last_trade_price":"14.7900","last_extended_hours_trade_price"vious:"14.7900","关闭前" 14.3600","adjusted_previous_close":"14.3600","previous_close_date":"2018-05-07","symbol":"SURF","trading_halted":false,"has_traded":true,"last_trade_price_source":"合并" ,"updated_at":"2018-05-08T20:01:21Z","instrument":" https://api.robinhood.com/instruments/43d56335-f2f6-4711-b650-55be2396f814/ "} ['{" ask_price":"14.9000","ask_size":100,"bid_price":"14.0100","bid_size":100,"last_trade_price":"14.7900","last_extended_hours_trade_price":"14.7900","104_close":"104 ,"adjusted_previous_close":"14.3600","previous_close_date":"2018-05-07","symbol":"SURF","trading_halted":false,"has_traded":true,"last_trade_price_source":"合并"," updated_at":"2018-05-08T20:01:21Z","instrument":" https://api.robinhood.com/instruments/43d56335-f2f6-4711-b650-55be2396f814/ "}']


The above results appear to point to the issue being related to the Spyder IDE.上述结果似乎指向与 Spyder IDE 相关的问题。


I have two questions:我有两个问题:

  1. Why am I getting this error?为什么我收到这个错误? It seems like other people do not get this error when running the tutorial code.其他人在运行教程代码时似乎没有收到此错误。 (Potentially answered: POSSIBLE BUG IN SPYDER3) (可能的回答:SPYDER3 中可能存在的 BUG)

    This seems to only happen in the spyder IDE.这似乎只发生在 spyder IDE 中。 I ran both snippets of code in from the cmd prompt and no error appeared.我从 cmd 提示符运行了两个代码片段,没有出现错误。 Thanks to @MikhailGerasimov for the suggestion.感谢@MikhailGerasimov 的建议。

  2. Given that I have two print commands (in the second snippet of code) and that only one set of "data" was printed, then why is data not getting back to the original call (results = loop.run_until_complete(get_async_urls(urls))) (Potentially answered: POSSIBLE BUG IN SPYDER3)鉴于我有两个打印命令(在第二段代码中)并且只打印了一组“数据”,那么为什么数据没有返回到原始调用(results = loop.run_until_complete(get_async_urls(urls)) ) (可能的回答:SPYDER3 中可能存在 BUG)

    This seems to only happen in the spyder IDE.这似乎只发生在 spyder IDE 中。 I ran the second snippet of code in from the cmd prompt and both prints appeared.我从 cmd 提示符运行了第二段代码,两个打印件都出现了。 Thanks to @MikhailGerasimov for the suggestion.感谢@MikhailGerasimov 的建议。




BOTH QUESTIONS HAVE (probably) BEEN ANSWERED.这两个问题(可能)都得到了回答。 I will reference this question when I submit an issue to spyder IDE.当我向 spyder IDE 提交问题时,我会参考这个问题。 I will continue to update this as things evolve on the spyder side of things.随着事物在 spyder 方面的发展,我将继续更新此内容。 If they come back and say the issue does not lie with them, then I will reopen the questions in a slightly different format.如果他们回来说问题不在于他们,那么我将以稍微不同的格式重新提出问题。

Thanks for the help!谢谢您的帮助!




Link to the referenced issue submission in Spyder IDE's github: https://github.com/spyder-ide/spyder/issues/7096链接到 Spyder IDE 的 github 中引用的问题提交: https : //github.com/spyder-ide/spyder/issues/7096




I have the same issue with Spyder, The only solution that worked for me was to use nest_asyncio我对 Spyder 有同样的问题,唯一对我有用的解决方案是使用nest_asyncio

install the nest_asyncio by using the command使用命令安装 nest_asyncio

pip install nest_asyncio

Add the below lines in your file在您的文件中添加以下几行

import nest_asyncio
nest_asyncio.apply()

And the issue must be fixed.而且这个问题必须解决。


From the docs's从文档的

By design asyncio does not allow its event loop to be nested.按照设计,asyncio 不允许嵌套其事件​​循环。 This presents a practical problem: When in an environment where the event loop is already running it's impossible to run tasks and wait for the result.这提出了一个实际问题:当在事件循环已经运行的环境中时,不可能运行任务并等待结果。 Trying to do so will give the error “RuntimeError: This event loop is already running”.尝试这样做会给出错误“RuntimeError:此事件循环已经在运行”。

The issue pops up in various environments, such as web servers, GUI applications and in Jupyter notebooks.该问题会在各种环境中出现,例如 Web 服务器、GUI 应用程序和 Jupyter 笔记本。

This module patches asyncio to allow nested use of asyncio.run and loop.run_until_complete.此模块修补 asyncio 以允许嵌套使用 asyncio.run 和 loop.run_until_complete。

The issue appears to be related to the IDE used (Spyder3).该问题似乎与使用的 IDE (Spyder3) 有关。 I tried running the code with PyCharm community edition last night.我昨晚尝试使用 PyCharm 社区版运行代码。 The code ran with no issues.代码运行没有问题。

I have submitted a bug to Spyder3.我已经向 Spyder3 提交了一个错误。

Looks to me Spyder runs its own event loop.在我看来,Spyder 运行自己的事件循环。 You cannot run two event loops in a single thread.您不能在单个线程中运行两个事件循环。

asyncio.run(coro, *, debug=False) asyncio.run(coro, *, debug=False)

This function cannot be called when another asyncio event loop is running in the same thread.当另一个异步事件循环在同一线程中运行时,无法调用此函数。

This is what worked for me.这对我有用。 I start my own loop if there is not other running loop:如果没有其他运行循环,我会开始自己的循环:

import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    await say_after(2, 'done')

await say_after(1, 'ahoy')    

loop = asyncio.get_event_loop()
print(loop) # <_WindowsSelectorEventLoop running=True closed=False debug=False>
if loop.is_running() == False:
    asyncio.run(main())
else:
    await main()

Perhaps I was lucky, but I downgraded Tornado.也许我很幸运,但我降级了 Tornado。 See "Can't invoke asyncio event_loop after tornado 5.0 update"请参阅“龙卷风 5.0 更新后无法调用 asyncio event_loop”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 结合 asyncio 和 aiohttp 时出现“RuntimeError:此事件循环已在运行” - "RuntimeError: This event loop is already running" when combine asyncio and aiohttp aiohttp:从正在运行的Web上调用asyncio应用程序:RuntimeError:此事件循环已在运行 - aiohttp: calling asyncio from a running web.Application: RuntimeError: This event loop is already running asyncio: RuntimeError 这个事件循环已经在运行 - asyncio: RuntimeError this event loop is already running 运行时错误:此事件循环已在 python 中运行 - RuntimeError: This event loop is already running in python Python RuntimeError:此事件循环已在运行 - Python RuntimeError: This event loop is already running RuntimeError:此事件循环已在 python 站点映射中运行 - RuntimeError: This event loop is already running in python sitemaping Flask asyncio aiohttp - RuntimeError:线程'Thread-2'中没有当前事件循环 - Flask asyncio aiohttp - RuntimeError: There is no current event loop in thread 'Thread-2' RuntimeError:无法关闭正在运行的事件循环 - RuntimeError: Cannot close a running event loop asyncio/aiohttp - create_task() 阻止事件循环,在“此事件循环已在运行”中收集结果 - asyncio/aiohttp - create_task() blocks event loop, gather results in “This event loop is already running ” asyncio create task and aiohttp, 'no running event loop' - asyncio create task and aiohttp , 'no running event loop'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM