Redirect output to file/stdout to a pager process.  Care is taken to
    restore the controlling tty stdio files to their original state.
490486
def pager_redirect(desc, *, pagercmd=None, istty=None, file=None,
                   substitutions=None):
    
    global _pager_active
    if file is None:
        file = sys.stdout
    if not pagercmd or not file.isatty() or _pager_active:
        yield
        return
    subs = {"desc": desc}
    if substitutions is not None:
        subs.update(substitutions)
    pagercmd = pagercmd.format(**subs)
    with tty_restoration():
        p = pager_process(pagercmd)
        if istty is None:
            p.stdin.isatty = file.isatty
        else:
            p.stdin.isatty = lambda: istty
        stdout_save = sys.stdout
        sys.stdout = p.stdin
        _pager_active = True
        try:
            yield
        finally:
            _pager_active = False
            sys.stdout = stdout_save
            try:
                p.stdin.close()
            except BrokenPipeError:
                pass
            while p.poll() is None:
                try:
                    p.wait()
                except KeyboardInterrupt:
                    pass
1198254
def handle_output(self, workunit, label, s):
    """"""
    if os.path.exists(self._html_dir):  # Make sure we're not immediately after a clean-all.
      path = os.path.join(self._html_dir, '{}.{}'.format(workunit.id, label))
      output_files = self._output_files[workunit.id]
      if path not in output_files:
        f = open(path, 'w')
        output_files[path] = f
      else:
        f = output_files[path]
      f.write(self._htmlify_text(s))
      # We must flush in the same thread as the write.
      f.flush()
354918
def handle_streams(stdout_stream, stderr_stream, &block)
        logger.debug "Monitoring stdout/stderr streams for output"
        streams = [stdout_stream, stderr_stream]
        until streams.empty?
          # Find which streams are ready for reading, timeout 0.1s
          selected, = select(streams, nil, nil, 0.1)

          # Try again if none were ready
          next if selected.nil? or selected.empty?

          selected.each do |stream|
            if stream.eof?
              logger.debug "Stream reached end-of-file"
              if @success.nil?
                logger.debug "Process hasn't finished, keeping stream"
              else
                logger.debug "Removing stream"
                streams.delete(stream)
              end
              next
            end

            while data = @reader.call(stream)
              data = ((@options[:mode] == :chars) ? data.chr : data)
              stream_name = (stream == stdout_stream) ? :stdout : :stderr
              output data, stream_name, &block unless block.nil?
              buffer data, stream_name unless @options[:no_buffer]
            end
          end
        end
      end
214041
def reprocess!
      new_original = Tempfile.new("paperclip-reprocess")
      new_original.binmode
      if old_original = to_file(:original)
        new_original.write( old_original.respond_to?(:get) ? old_original.get : old_original.read )
        new_original.rewind

        @queued_for_write = { :original => new_original }
        post_process

        old_original.close if old_original.respond_to?(:close)

        save
      else
        true
      end
    rescue Errno::EACCES => e
      warn "#{e} - skipping file"
      false
    end
622000
def redirectSTDOUTtoDebugFile():
    """"""
    import sys
    kwargs = {}
    if sys.version_info >= (3,):
        kwargs["encoding"] = "utf8"
    sys.stdout = open(
        os.path.join(
            getDebugDirectory(),
            "{0}.stdout".format(getDebugIdentifier()),
        ),
        "w",
        1, # Buffering by line
        **kwargs
    )
    sys.stderr = open(
        os.path.join(
            getDebugDirectory(),
            "{0}.stderr".format(getDebugIdentifier()),
        ),
        "w",
        1, # Buffering by line
        **kwargs
    )
495744
def flushed_print(*args, **kwargs):
    
    print(*args, **kwargs)
    file = kwargs.get('file', sys.stdout)
    file.flush() if file is not None else sys.stdout.flush()
393469
def israw(self, **kwargs):
        

        if self.raw is None:
            self.raw = self.stdout.isatty() and self.is_process_tty()

        return self.raw
366839
def tee_output_python():
    """"""
    buffer = StringIO()
    out = CapturedStdout(buffer)
    orig_stdout, orig_stderr = sys.stdout, sys.stderr
    flush()
    sys.stdout = TeeingStreamProxy(sys.stdout, buffer)
    sys.stderr = TeeingStreamProxy(sys.stderr, buffer)
    try:
        yield out
    finally:
        flush()
        out.finalize()
        sys.stdout, sys.stderr = orig_stdout, orig_stderr
1044142
def _tty_stdio(cls, env):
    """"""
    # If all stdio is a tty, there's only one logical I/O device (the tty device). This happens to
    # be addressable as a file in OSX and Linux, so we take advantage of that and directly open the
    # character device for output redirection - eliminating the need to directly marshall any
    # interactive stdio back/forth across the socket and permitting full, correct tty control with
    # no middle-man.
    stdin_ttyname, stdout_ttyname, stderr_ttyname = NailgunProtocol.ttynames_from_env(env)
    assert stdin_ttyname == stdout_ttyname == stderr_ttyname, (
      'expected all stdio ttys to be the same, but instead got: {}\n'
      'please file a bug at http://github.com/pantsbuild/pants'
      .format([stdin_ttyname, stdout_ttyname, stderr_ttyname])
    )
    with open(stdin_ttyname, 'rb+', 0) as tty:
      tty_fileno = tty.fileno()
      with stdio_as(stdin_fd=tty_fileno, stdout_fd=tty_fileno, stderr_fd=tty_fileno):
        def finalizer():
          termios.tcdrain(tty_fileno)
        yield finalizer
487578
def fill_pager(self, page):
        
        tty_size = os.popen("stty size", "r").read().split()
        rows = int(tty_size[0]) - 1
        lines = sum(1 for line in page.splitlines())
        diff = rows - lines
        fill = "\n" * diff
        if diff > 0:
            return fill
        else:
            return ""
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()
974231
def redirect_std():
    
    stdin = sys.stdin
    stdout = sys.stdout
    if not sys.stdin.isatty():
        sys.stdin = open_raw("/dev/tty", "r", 0)
    if not sys.stdout.isatty():
        sys.stdout = open_raw("/dev/tty", "w", 0)

    return stdin, stdout
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)
1053856
def redirect_stdout(self, enabled=True, log_level=logging.INFO):
        
        if enabled:
            if self.__stdout_wrapper:
                self.__stdout_wrapper.update_log_level(log_level=log_level)
            else:
                self.__stdout_wrapper = StdOutWrapper(logger=self, log_level=log_level)

            self.__stdout_stream = self.__stdout_wrapper
        else:
            self.__stdout_stream = _original_stdout

        # Assign the new stream to sys.stdout
        sys.stdout = self.__stdout_stream
1278096
def _on_process_stdout_ready(self):
        
        if not self:
            return
        o = self.readAllStandardOutput()
        try:
            output = bytes(o).decode(self._encoding)
        except TypeError:
            output = bytes(o.data()).decode(self._encoding)
        for line in output.splitlines():
            self._srv_logger.log(1, line)
658210
def outReceived(self, data):
        

        if self.stdout:
            self.stdout.write(data.decode('ascii'))

        # minor hack: we can't try this in connectionMade because
        # that's when the process first starts up so Tor hasn't
        # opened any ports properly yet. So, we presume that after
        # its first output we're good-to-go. If this fails, we'll
        # reset and try again at the next output (see this class'
        # tor_connection_failed)
        txtorlog.msg(data)
        if not self.attempted_connect and self.connection_creator \
                and b'Opening Control listener' in data:
            self.attempted_connect = True
            # hmmm, we don't "do" anything with this Deferred?
            # (should it be connected to the when_connected
            # Deferreds?)
            d = self.connection_creator()
            d.addCallback(self._tor_connected)
            d.addErrback(self._tor_connection_failed)
996790
def regenerateToOutputFile(outFile, checkNoChanges = false)
      executeRubyComponents
      @pageObject.process
      writeRegeneratedFile(outFile, checkNoChanges, checkNoChanges)
    end