Asyncio协程从未等待的错误

编程入门 行业动态 更新时间:2024-10-26 19:26:47
本文介绍了Asyncio协程从未等待的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在这里无法解决和理解问题。我正在使用一个示例来学习Asyncio,但是我使用的代码与我的相似,但是我的给出了一条错误消息:

I'm having trouble fixing and understanding the problem here. I'm using an example to learn Asyncio but the code I'm using is similar to mine but mine gives an error message saying:

sys:1:RuntimeWarning:从未等待协程'run_script'

sys:1: RuntimeWarning: coroutine 'run_script' was never awaited

请提供任何帮助,我们将不胜感激。下面是我的代码

Please any help will be greatly appreciated. Below is my code

async def run_script(script): print("Run", script) await asyncio.sleep(1) os.system("python " + script)

并且我正在像这样运行它

and I'm running it like this

for script in os.listdir(): if script.endswith(".py"): scripts.append(run_script(script)) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather(scripts)) loop.close()

推荐答案

为@ dim提到了代码中的错别字,还需要注意 os.system 是同步运行的,这意味着文件夹中的脚本将按顺序运行,而不是在

As @dim mentioned what's the typo in your code, you also need to be aware os.system is running in synchronous, which means scripts in your folder will be run in sequence instead of in asynchronous way.

要了解这一点,请添加名为 hello_world.py 的文件:

To understand that, add file called hello_world.py:

import time time.sleep(2) print('hello world')

如果您以脚本形式运行脚本低点,将花费您2s + 2s = 4s:

if you run you script as follows, it will cost you 2s + 2s = 4s:

loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.gather( *[run_script('hello_world.py') for _ in range(2)] ) )

因此,要解决此问题,可以使用 asyncio.subprocess 模块:

So to solve this issue, you can use asyncio.subprocess module:

from asyncio import subprocess async def run_script(script): process = await subprocess.create_subprocess_exec('python', script) try: out, err = await processmunicate() except Exception as err: print(err)

然后,由于它异步运行,因此只需花费2秒钟。

Then it will cost you only 2 sec, because it is running asynchronously.

更多推荐

Asyncio协程从未等待的错误

本文发布于:2023-11-23 11:11:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621239.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   Asyncio

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!