Redirect stderr for subprocesses to /dev/null

    Silences copious compilation messages.

    Returns
    -------
    orig_stderr : file descriptor
        Copy of original stderr file descriptor
322939
def _redirect_stderr():
    
    sys.stderr.flush()
    stderr_fileno = sys.stderr.fileno()
    orig_stderr = os.dup(stderr_fileno)
    devnull = os.open(os.devnull, os.O_WRONLY)
    os.dup2(devnull, stderr_fileno)
    os.close(devnull)
    return orig_stderr
674434
def unregisterStdErr(func):
    
    try:
        sys.stderr.hooks.remove(weakref.ref(func))
    except (AttributeError, ValueError):
        pass
182551
def _log_to_stderr(self, record):
    
    # emit() is protected by a lock in logging.Handler, so we don't need to
    # protect here again.
    old_stream = self.stream
    self.stream = sys.stderr
    try:
      super(PythonHandler, self).emit(record)
    finally:
      self.stream = old_stream
886355
def _close_stdout_stderr_streams(self):
        

        # we don't have tee_file's in headless mode
        if self._stdout_tee.tee_file is not None:
            self._stdout_tee.tee_file.close()
        if self._stderr_tee.tee_file is not None:
            self._stderr_tee.tee_file.close()

        # TODO(adrian): we should close these even in headless mode
        # but in python 2 the read thread doesn't stop on its own
        # for some reason
        self._stdout_tee.close_join()
        self._stderr_tee.close_join()

        if self._cloud:
            # not set in dry run mode
            self._stdout_stream.close()
            self._stderr_stream.close()

        self._output_log.f.close()
        self._output_log = None
116868
def stderr():
    

    # We write all of the data to stderr with bytes, typically io.BytesIO. stderr in Python2
    # accepts bytes but Python3 does not. This is due to a type change on the attribute. To keep
    # this consistent, we leave Python2 the same and get the .buffer attribute on stderr in Python3
    byte_stderr = sys.stderr

    if sys.version_info.major > 2:
        byte_stderr = sys.stderr.buffer  # pylint: disable=no-member

    return byte_stderr
939636
def report_stderr(host, stderr):
    
    lines = stderr.readlines()
    if lines:
        print("STDERR from {host}:".format(host=host))
        for line in lines:
            print(line.rstrip(), file=sys.stderr)
266970
def error(*args, **kwargs):  # pragma: nocover
    
    kwargs['file'] = sys.stderr
    print("\n\tERROR:", *args, **kwargs)
    sys.exit(1)
1310464
def warning(self, s):
        
        print("   WARNING: '%s', %s" % (self.src_id, s), file=sys.stderr)
959000
def popen(self, stdout, stderr):
        
        self.logger.info('Executing command: %s', self.command_str)
        return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr)
287107
def stderr_avail(self):
        """"""
        data = self.interpreter.stderr_write.empty_queue()
        if data:
            self.write(data, error=True)
            self.flush(error=True)
990035
def redirect_stderr(self, enabled=True, log_level=logging.ERROR):
        
        if enabled:
            if self.__stderr_wrapper:
                self.__stderr_wrapper.update_log_level(log_level=log_level)
            else:
                self.__stderr_wrapper = StdErrWrapper(logger=self, log_level=log_level)

            self.__stderr_stream = self.__stderr_wrapper
        else:
            self.__stderr_stream = _original_stderr

        # Assign the new stream to sys.stderr
        sys.stderr = self.__stderr_stream
799884
def daemonize(enable_stdio_inheritance=False,
              auto_close_fds=True,
              keep_fds=None):   # pragma    nocover
    
    if os.fork():
        os._exit(0)
    os.setsid()

    if os.fork():
        os._exit(0)

    os.umask(0o22)

    # In both the following any file descriptors above stdin
    # stdout and stderr are left untouched. The inheritence
    # option simply allows one to have output go to a file
    # specified by way of shell redirection when not wanting
    # to use --error-log option.

    if not enable_stdio_inheritance:
        # Remap all of stdin, stdout and stderr on to
        # /dev/null. The expectation is that users have
        # specified the --error-log option.

        if keep_fds:
            keep_fds = set(keep_fds)
            for fd in range(0, 3):
                if fd not in keep_fds:
                    try:
                        os.close(fd)
                    except OSError:
                        pass
        else:
            os.closerange(0, 3)

        fd_null = os.open(REDIRECT_TO, os.O_RDWR)

        if fd_null != 0:
            os.dup2(fd_null, 0)

        os.dup2(fd_null, 1)
        os.dup2(fd_null, 2)

    else:
        fd_null = os.open(REDIRECT_TO, os.O_RDWR)

        # Always redirect stdin to /dev/null as we would
        # never expect to need to read interactive input.

        if fd_null != 0:
            os.close(0)
            os.dup2(fd_null, 0)

        # If stdout and stderr are still connected to
        # their original file descriptors we check to see
        # if they are associated with terminal devices.
        # When they are we map them to /dev/null so that
        # are still detached from any controlling terminal
        # properly. If not we preserve them as they are.
        #
        # If stdin and stdout were not hooked up to the
        # original file descriptors, then all bets are
        # off and all we can really do is leave them as
        # they were.
        #
        # This will allow 'gunicorn ... > output.log 2>&1'
        # to work with stdout/stderr going to the file
        # as expected.
        #
        # Note that if using --error-log option, the log
        # file specified through shell redirection will
        # only be used up until the log file specified
        # by the option takes over. As it replaces stdout
        # and stderr at the file descriptor level, then
        # anything using stdout or stderr, including having
        # cached a reference to them, will still work.

        def redirect(stream, fd_expect):
            try:
                fd = stream.fileno()
                if fd == fd_expect and stream.isatty():
                    os.close(fd)
                    os.dup2(fd_null, fd)
            except AttributeError:
                pass

        redirect(sys.stdout, 1)
        redirect(sys.stderr, 2)
704728
def stderr_file(self):
        """"""
        stderr_file = None
        if self.connection_file is not None:
            stderr_file = self.kernel_id + '.stderr'
            if self.stderr_dir is not None:
                stderr_file = osp.join(self.stderr_dir, stderr_file)
            else:
                try:
                    stderr_file = osp.join(get_temp_dir(), stderr_file)
                except (IOError, OSError):
                    stderr_file = None
        return stderr_file
612409
def log_hack
      read_stderr, write_stderr = IO.pipe

      fork do
        write_stderr.close

        read_stderr.each do |l|
          @log.trace "GFS: #{l.chomp.strip}"
        end

        read_stderr.close
      end

      old_stderr = STDERR.clone

      STDERR.reopen(write_stderr)
      STDERR.sync = true

      begin
        # Execute all tasks
        yield if block_given?
      ensure
        STDERR.reopen(old_stderr)
      end

      write_stderr.close
      read_stderr.close

      Process.wait
    end
890702
def Exit(msg, code=1):
    
    print >> sys.stderr, msg
    sys.exit(code)
1343783
async def stderr(self) -> AsyncGenerator[str, None]:
        """"""
        await self.wait_running()
        async for line in self._subprocess.stderr:  # type: ignore
            yield line
140544
def redirect_stdout(self):
        """"""
        self.hijacked_stdout = sys.stdout
        self.hijacked_stderr = sys.stderr
        # 0 must be set as the buffer, otherwise lines won't get logged in time.
        sys.stdout = open(self.hitch_dir.driverout(), "ab", 0)
        sys.stderr = open(self.hitch_dir.drivererr(), "ab", 0)