我无法解决和理解这里的问题。我正在使用一个示例来学习 Asyncio,但我使用的代码与我的代码类似,但我的代码给出了一条错误消息:
sys:1:运行时警告:从未等待协程“run_script”
请提供任何帮助,我们将不胜感激。下面是我的代码
async def run_script(script):
print("Run", script)
await asyncio.sleep(1)
os.system("python " + script)
我像这样运行它
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
以同步方式运行,这意味着文件夹中的脚本将按顺序运行,而不是以异步方式运行。
要理解这一点,请添加名为你好世界.py:
import time
time.sleep(2)
print('hello world')
如果您按如下方式运行脚本,则将花费您 2 秒 + 2 秒 = 4 秒:
loop = asyncio.get_event_loop()
loop.run_until_complete(
asyncio.gather(
*[run_script('hello_world.py') for _ in range(2)]
)
)
所以要解决这个问题,你可以使用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 秒,因为它是异步运行的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)