我应该如何在Python中包装交互式子进程(例如shell)

2024-06-26 00:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python3中使用subprocess模块为adb二进制文件编写一个简单的包装器模块,但是“shell”命令可以运行单次、一次性命令,也可以不带参数运行交互式shell。在

在某个时候,我(或其他人)可能会使用类似Vte的东西在GUI中利用它,但是我不知道我的函数返回什么是合理的,或者我是否应该在这个实例中使用Popen。在


Tags: 模块文件实例函数命令利用参数二进制
1条回答
网友
1楼 · 发布于 2024-06-26 00:18:35

当我用python实现ADB的包装器时,我选择使用subprocess模块。我发现check_output(...)函数很方便,因为它可以验证命令返回的状态是否为0。如果check_output(...)执行的命令返回非零状态,则抛出CalledProcessError。我发现这很方便,因为我可以向用户报告一个特定的ADB命令未能运行。在

下面是我如何实现该方法的一个片段。请随意参考我的ADB wrapper实现。在

    def _run_command(self, cmd):
    """
    Execute an adb command via the subprocess module. If the process exits with
    a exit status of zero, the output is encapsulated into a ADBCommandResult and
    returned. Otherwise, an ADBExecutionError is thrown.
    """
    try:
        output = check_output(cmd, stderr=subprocess.STDOUT)
        return ADBCommandResult(0,output)
    except CalledProcessError as e:
        raise ADBProcessError(e.cmd, e.returncode, e.output) 

相关问题 更多 >