Get the OS appropriate handle for the corresponding output stream.

    :param str stream: The the stream to get the handle for
    :return: A handle to the appropriate stream, either a ctypes buffer
             or **sys.stdout** or **sys.stderr**.
190563
def get_stream_handle(stream=sys.stdout):
    
    handle = stream
    if os.name == "nt":
        from ctypes import windll

        handle_id = WIN_STDOUT_HANDLE_ID
        handle = windll.kernel32.GetStdHandle(handle_id)
    return handle
348940
def bread(stream):
    
    if hasattr(stream, "read"):
        return bdecode(stream.read())
    else:
        handle = open(stream, "rb")
        try:
            return bdecode(handle.read())
        finally:
            handle.close()
600221
def close(self):
        

        if self.stream is None:
            return

        try:
            self.stream.isatty()

            if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]:
                return
        except AttributeError:
            pass
        except ValueError:
            # raised when executing an operation to a closed stream
            pass

        try:
            from _pytest.compat import CaptureIO
            from _pytest.capture import EncodedFile

            if isinstance(self.stream, (CaptureIO, EncodedFile)):
                # avoid closing streams for pytest
                return
        except ImportError:
            pass

        try:
            from ipykernel.iostream import OutStream

            if isinstance(self.stream, OutStream):
                # avoid closing streams for Jupyter Notebook
                return
        except ImportError:
            pass

        try:
            self.stream.close()
        except AttributeError:
            self._logger.logger.warn(
                "the stream has no close method implementation: type={}".format(type(self.stream))
            )
        finally:
            self._stream = None
277538
def handle_stderr(stderr_pipe):
    
    stderr_output = stderr_pipe.read()

    if len(stderr_output) > 0:
        click.secho("\n__ Error Output {0}".format('_'*62), fg='white',
                    bold=True)
        click.echo(stderr_output)

    return True
745121
def get_wrapped_stream(stream):
    

    if stream is None:
        raise TypeError("must provide a stream to wrap")
    encoding = getattr(stream, "encoding", None)
    encoding = get_output_encoding(encoding)
    return StreamWrapper(stream, encoding, "replace", line_buffering=True)
768397
def close_stream(self):
        
        if self.fout:
            fout = self.fout
            fout_fn = self.fout_fn
            self.fout.flush()
            self.fout.close()
            self.fout = None
            self.fout_fn = None
            return fout_fn
278614
def captured_output(stream_name):
    
    orig_stdout = getattr(sys, stream_name)
    setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
    try:
        yield getattr(sys, stream_name)
    finally:
        setattr(sys, stream_name, orig_stdout)
215668
def eout(s):
    

    if allow_print: 
       if con_encoding=='':
          x=sys.stdin.encoding
          if x==None: 
             b=s.encode()
          else:
             b=s.encode(x, 'ignore')
       else:
          b=s.encode(con_encoding, 'ignore')

       if sys.version_info[0]>2:
          try: # We encountered issues on ipython with Anaconda
               # and hence made this work around
             sys.stderr.buffer.write(b)
             sys.stderr.buffer.write(b'\n')
          except Exception as e: 
             sys.stderr.write(s)
             pass
       else:
          sys.stderr.write(b)

    sys.stderr.flush()

    return None
670950
def set_stream(self, stream):
        

        for handler in self.handlers[:]:
            if isinstance(handler, logging.StreamHandler):
                self.handlers.remove(handler)

        if stream is not None:
            stream_handler = logging.StreamHandler(stream)
            stream_handler.addFilter(_StreamHandlerEchoFilter())
            stream_handler.setFormatter(logging.Formatter('%(message)s'))
            self.addHandler(stream_handler)

        self.stream = stream
741414
def stderr_handle(self):
        """"""
        if self.stderr_file is not None:
            # Needed to prevent any error that could appear.
            # See issue 6267
            try:
                handle = codecs.open(self.stderr_file, 'w', encoding='utf-8')
            except Exception:
                handle = None
        else:
            handle = None

        return handle
1340929
def _stream(self, char):
        

        num = ord(char)
        if num in self.basic:
            self.dispatch(self.basic[num])
        elif num == ctrl.ESC:
            self.state = "escape"
        elif num == 0x00:
            # nulls are just ignored.
            pass
        else: 
            self.dispatch("print", char)
664264
def decode(stream, *args, **kwargs):
    
    encoding = kwargs.pop('encoding', DEFAULT_ENCODING)
    decoder = get_decoder(encoding, stream, *args, **kwargs)

    return decoder
488664
def _check_stream(stream):
    ''''''
    if not isinstance(stream, type(_sys.stderr)):
        raise TypeError("The stream given ({}) is not a file object.".format(stream))
384585
def _using_stdout(self):
        
        if WINDOWS and colorama:
            # Then self.stream is an AnsiToWin32 object.
            return self.stream.wrapped is sys.stdout

        return self.stream is sys.stdout
205502
def _unbuffered(self, proc, stream='stdout'):
        
        if self.working_handler is not None:
            t = Thread(target=self._handle_process, args=(proc, stream))
            t.start()
        out = getattr(proc, stream)
        try:
            for line in iter(out.readline, ""):
                yield line.rstrip()
        finally:
            out.close()
502976
def stderr(self):
        
        streams = self._payload.get('streams', None)
        return streams[1] if streams is not None and len(streams) >= 2 else ''
1082795
def stderr_redirected(to=os.devnull):
    
    fd = sys.stderr.fileno()

    # assert that Python and C stdio write using the same file descriptor
    # assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stderr")) == fd == 1
    
    def _redirect_stderr(to):
        sys.stderr.close()  # + implicit flush()
        os.dup2(to.fileno(), fd)  # fd writes to 'to' file
        sys.stderr = os.fdopen(fd, 'w')  # Python writes to fd

    with os.fdopen(os.dup(fd), 'w') as old_stderr:
        with open(to, 'w') as file:
            _redirect_stderr(to=file)
        try:
            yield  # allow code to be run with the redirected stderr
        finally:
            _redirect_stderr(to=old_stderr)