欢迎访问宙启技术站
智能推送

使用Python的popen2模块实现命令行交互。

发布时间:2024-01-07 22:16:06

popen2模块是Python标准库中的一个模块,它提供了一个简单的接口来启动子进程并与其进行交互。我们可以使用此模块来执行命令行命令,并通过输入和输出来与子进程进行交互。

下面是一个使用popen2模块进行命令行交互的示例:

import sys
from subprocess import Popen, PIPE


def interact_with_command(command):
    # 启动子进程并创建输入输出流
    process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)

    # 指定需要输入给子进程的命令
    commands_to_send = [
        "command1",
        "command2",
        "command3",
        "exit"
    ]

    # 向子进程发送命令并获取输出
    for command in commands_to_send:
        process.stdin.write(command.encode())
        process.stdin.write(b"
")
        process.stdin.flush()

        # 从子进程的输出流读取输出
        output = process.stdout.readline().decode().strip()

        # 打印子进程的输出
        print(output)

    # 关闭子进程的输入和输出流
    process.stdin.close()
    process.stdout.close()


if __name__ == "__main__":
    # 在这里调用interact_with_command函数并传递需要执行的命令
    command = sys.argv[1] if len(sys.argv) > 1 else "python --version"
    interact_with_command(command)

这个示例中,我们首先导入了sys和subprocess的Popen和PIPE类。然后定义了一个名为interact_with_command的函数来执行命令行交互。在函数内部,我们使用Popen类来创建一个子进程,并指定输入和输出的管道。

然后,我们定义了一个以空格分隔的命令列表commands_to_send,这些命令将被发送给子进程。我们使用process.stdin.write将每个命令发送给子进程的标准输入流,并使用process.stdin.flush刷新输入流。

接下来,我们使用process.stdout.readline从子进程的标准输出流读取输出,并使用decode方法将其转换为字符串。然后我们打印输出。

最后,我们使用process.stdin.close关闭子进程的输入流,使用process.stdout.close关闭子进程的输出流。

在main函数中,我们从命令行参数或者使用默认命令来调用interact_with_command函数。在这个示例中,默认的命令是"python --version",它将输出Python的版本号。

你可以通过传递不同的命令来测试这个示例,看看它是如何和子进程进行交互的。请注意,这个示例中使用了shell=True来启动子进程,这意味着你可以执行一些常规的命令,但也可能存在一些安全风险,请确保你只执行可信任的命令。

希望这个使用popen2模块实现命令行交互的示例对你有所帮助!