Asyncio协程永远不会等待错误

Tus*_*rtz 5 python coroutine python-asyncio

我在这里修复和理解问题时遇到了麻烦.我正在使用一个示例来学习Asyncio,但我使用的代码与我的类似,但我的错误消息说:

sys:1:RuntimeWarning:从未等待过coroutine'run_script'

如有任何帮助,将不胜感激.以下是我的代码

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

而且我这样运行它

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()
Run Code Online (Sandbox Code Playgroud)

Zho*_*uan 5

由于@dim提到了代码中的拼写错误,您还需要注意os.system同步运行,这意味着文件夹中的脚本将按顺序而不是以异步方式运行.

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

import time
time.sleep(2)
print('hello world')
Run Code Online (Sandbox Code Playgroud)

如果你运行脚本如下,它将花费你2s + 2s = 4s:

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

所以要解决这个问题,你可以使用asyncio.subprocess模块:

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)
Run Code Online (Sandbox Code Playgroud)

然后它将花费你只有2秒,因为它是异步运行.