def monitor_command(cmd, timeout=None):
    cmdStr = cmd
    shell = True
    if isinstance(cmd, list):
        cmdStr = " ".join(cmd)
        shell = False

    assert cmdStr, "empty command passed to monitor_command"

    log.debug('command: {0}'.format(cmdStr))

    # sanitize PATH if we are running in a virtualenv
    env = copy(environ)
    if hasattr(sys, "real_prefix"):
        env["PATH"] = string.replace(env["PATH"], "{0}/bin:".format(sys.prefix), "")

    proc = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True, shell=shell, env=env)
    set_nonblocking(proc.stdout)
    set_nonblocking(proc.stderr)

    if timeout:
        alarm(timeout)

        def handle_sigalarm(*_):
            proc.terminate()
        signal(SIGALRM, handle_sigalarm)

    io = [proc.stdout, proc.stderr]

    std_out = ""
    std_err = ""
    while True:
        # if we got eof from all pipes then stop polling
        if not io:
            break
        reads, _, _ = select(io, [], [])
        for fd in reads:
            buf = fd.read(4096)
            if len(buf) == 0:
                # got eof
                io.remove(fd)
            else:
                if fd == proc.stderr:
                    log.debug("STDERR: {0}".format(buf))
                    std_err += buf
                else:
                    if buf[-1] == "\n":
                        log.debug(buf[:-1])
                    else:
                        log.debug(buf)
                    std_out += buf

    proc.wait()
    alarm(0)
    status_code = proc.returncode
    log.debug("status code: {0}".format(status_code))
    return CommandResult(status_code == 0, Response(cmdStr, std_err, std_out, status_code))
dataset/ETHPy150Open Netflix/aminator/aminator/util/linux.py/monitor_command/original