0

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

在某些时候,我(或其他人)可能会使用 Vte 之类的东西在 GUI 中利用它,但我不知道我的函数返回什么是理智的,或者我什至应该在这种情况下使用 Popen。

4

1 回答 1

2

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

这是我如何实现该方法的片段。请随意参考我的ADB 包装器实现。

    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) 
于 2013-10-10T11:39:15.557 回答