'Drain the subprocesses output streams, writing the collected output
to the result. If a writer thread (writing to the subprocess) is given,
make sure it\'s joined before returning. If a stdin stream is given,
close it before returning.'

def _collect_output(self, process, result, writer=None, stdin=None):

    stderr = codecs.getreader(self.encoding)(process.stderr)
    rr = threading.Thread(target=self._read_response, args=(stderr, result))
    rr.setDaemon(True)
    logger.debug('stderr    reader:    %r', rr)
    rr.start()
    stdout = process.stdout
    dr = threading.Thread(target=self._read_data, args=(stdout, result))
    dr.setDaemon(True)
    logger.debug('stdout    reader:    %r', dr)
    dr.start()
    dr.join()
    rr.join()
    if (writer is not None):
        writer.join()
    process.wait()
    if (stdin is not None):
        try:
            stdin.close()
        except IOError:
            pass
    stderr.close()
    stdout.close()
