#!/usr/bin/env python

import os
import select

############################################################################
def ExecWithCapture(command, argv, searchPath = 0, root = '/', stdin = 0,
        catchfd = 1, closefd = -1):

    if not os.access(root + command, os.X_OK) and not searchPath:
        raise RuntimeError, command + " can not be run"

    (read, write) = os.pipe()
    childpid = os.fork()
    if (not childpid):
        if (root and root != '/'): os.chroot(root)
        os.dup2(write, catchfd)
        os.close(write)
        os.close(read)

        if closefd != -1:
            os.close(closefd)
        if stdin:
            os.dup2(stdin, 0)
            os.close(stdin)
        if searchPath:
            os.execvp(command, argv)
        else:
            os.execv(command, argv)
        sys.exit(1)
    os.close(write)

    rc = ""
    s = "1"
    while s:
        select.select([read], [], [])
        s = os.read(read, 1000)
        rc = rc + s

    os.close(read)

    try:
        os.waitpid(childpid, 0)
    except OSError, (errno, msg):
        print __name__, "waitpid:", msg

    return rc
