view treepkg/run.py @ 0:f78a02e79c84

initial checkin
author Bernhard Herzog <bh@intevation.de>
date Tue, 06 Mar 2007 17:37:32 +0100
parents
children fee641fec94e
line wrap: on
line source
# Copyright (C) 2007 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, **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")
    ret = subprocess.call(command, **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)