Search code examples
pythonshelladbwrappervte

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


I'm writing a simple wrapper module in Python3 for the adb binary using the subprocess module, however the 'shell' command can either run single, one-shot commands or with no arguments run an interactive shell.

At some point I (or someone else) may use something like Vte to leverage this in a GUI, but I'm lost as to what is sane for my function to return, or if I should even be using Popen in this instance.


Solution

  • I chose to use the subprocess module when I implemented a wrapper for ADB in python. I found that the check_output(...) function came in handy because it would verify the command would return with a 0 status. If the command executed by check_output(...) returns a non-zero status a CalledProcessError is thrown. I found this convenient as I could than report back to the user a specific ADB command failed to run.

    Here is a snippet of how I implemented the method. Feel free to reference my implementation of the 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)