首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从Python异步运行外部命令?

要从Python异步运行外部命令,可以使用asyncio库。asyncio库是Python的异步I/O框架,它允许您编写并发代码,使用asyncawait关键字处理异步任务。以下是一个简单的示例,演示如何使用asyncio异步运行外部命令:

代码语言:python
复制
import asyncio
import subprocess

async def run_command(command):
    process = await asyncio.create_subprocess_shell(
        command,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )

    stdout, stderr = await process.communicate()

    if process.returncode != 0:
        raise Exception(f"Command '{command}' failed with error: {stderr.decode('utf-8')}")

    return stdout.decode('utf-8')

async def main():
    command1 = "echo 'Hello, World!'"
    command2 = "echo 'Goodbye, World!'"

    task1 = asyncio.create_task(run_command(command1))
    task2 = asyncio.create_task(run_command(command2))

    output1 = await task1
    output2 = await task2

    print(f"Output from command 1: {output1}")
    print(f"Output from command 2: {output2}")

if __name__ == "__main__":
    asyncio.run(main())

在这个示例中,我们定义了一个名为run_command的异步函数,它使用asyncio.create_subprocess_shell创建一个子进程,并使用await process.communicate()等待子进程完成。然后,我们在main函数中创建两个任务,分别运行两个外部命令,并使用await等待它们完成。最后,我们打印命令的输出。

这个示例可以帮助您从Python异步运行外部命令。请注意,这个示例仅适用于Python 3.7及更高版本。如果您使用的是较旧的Python版本,可能需要使用其他方法来实现异步。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券