~launchpad-pqm/launchpad/devel

8687.15.18 by Karl Fogel
Add the copyright header block to files under lib/canonical/.
1
# Copyright 2009 Canonical Ltd.  This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
5294.1.3 by Jeroen Vermeulen
Addressed BjornT's points prior to resuming formal review.
3
4
"""Helper functions for running external commands."""
5
6
__metaclass__ = type
7675.1116.6 by Jeroen Vermeulen
Helper tests, and small fry.
7
__all__ = [
8
    'run_command',
9
    'run_script',
10
    ]
5294.1.3 by Jeroen Vermeulen
Addressed BjornT's points prior to resuming formal review.
11
12
import subprocess
13
import sys
14
15
16
def run_command(command, args=None, input=None, shell=False):
17
    """Run an external command in a separate process.
18
19
    :param command: executable to run.
20
    :param args: optional list of command-line arguments.
21
    :param input: optional text to feed to command's standard input.
22
    :param shell: passed directly to `subprocess.Popen`.
23
    :return: tuple of return value, standard output, and standard error.
24
    """
25
    command_line = [command]
26
    if args:
27
        command_line.extend(args)
28
    if input is not None:
29
        stdin = subprocess.PIPE
30
    else:
31
        stdin = None
32
33
    child = subprocess.Popen(
34
        command_line, stdin=stdin, stdout=subprocess.PIPE,
35
        stderr=subprocess.PIPE)
36
    stdout, stderr = child.communicate(input)
37
    result = child.wait()
38
    return (result, stdout, stderr)
39
40
41
def run_script(script, args=None, input=None):
42
    """Run a Python script in a child process, using current interpreter.
43
44
    :param script: Python script to run.
45
    :param args: optional list of command-line arguments.
46
    :param input: optional string to feed to standard input.
47
    :return: tuple of return value, standard output, and standard error.
48
    """
49
    interpreter_args = [script]
50
    if args:
51
        interpreter_args.extend(args)
52
53
    return run_command(sys.executable, interpreter_args, input)