繁体   English   中英

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

[英]How should I wrap an interactive subprocess (eg. shell) in Python

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

在某些时候,我(或其他人)可能会使用Vte之类的东西在GUI中利用此功能,但是我迷失了我的函数返回的理智之处,或者甚至在这种情况下我都应该使用Popen。

当我在python中为ADB实现包装器时,我选择使用子流程模块。 我发现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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM