view treepkg/run.py @ 124:e08b4b09d35f

New parameter treepkg.run.call: extra_env for additional environment variables passed to the subprocess. Also add a test case.
author Bernhard Herzog <bh@intevation.de>
date Thu, 22 May 2008 12:44:43 +0000
parents fee641fec94e
children a68a4e22549c
line wrap: on
line source
# Copyright (C) 2007, 2008 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with the software for details.

"""Helper functions to run subprocesses in various ways"""

import os
import subprocess


class SubprocessError(EnvironmentError):

    def __init__(self, command, returncode):
        EnvironmentError.__init__(self,
                                  "Command %r finished with return code %d"
                                  % (command, returncode))
        self.returncode = returncode


def call(command, suppress_output=False, extra_env=None, **kw):
    """Run command as a subprocess and wait until it is finished.

    The command should be given as a list of strings to avoid problems
    with shell quoting.  If the command exits with a return code other
    than 0, a SubprocessError is raised.
    """
    if suppress_output:
        kw["stdout"] = open(os.devnull, "w")
        kw["stderr"] = open(os.devnull, "w")
    env = kw.pop("env", None)
    if extra_env:
        if env is None:
            env = os.environ.copy()
        env.update(extra_env)
    ret = subprocess.call(command, env=env, **kw)
    if ret != 0:
        raise SubprocessError(command, ret)


def capture_output(command, **kw):
    """Return the stdout and stderr of the command as a string

    The command should be given as a list of strings to avoid problems
    with shell quoting.  If the command exits with a return code other
    than 0, a SubprocessError is raised.
    """
    proc = subprocess.Popen(command, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT, **kw)
    output = proc.communicate()[0]
    if proc.returncode != 0:
        raise SubprocessError(command, proc.returncode)
    return output
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)