Asyncio协程从未等待的错误 [英] Asyncio coroutine never awaited error
问题描述
我在这里无法解决和理解问题。我正在使用一个示例来学习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 process.communicate()
except Exception as err:
print(err)
然后,由于它异步运行,因此只需花费2秒钟。
Then it will cost you only 2 sec, because it is running asynchronously.
这篇关于Asyncio协程从未等待的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!