Sets up STDOUT and STDERR streams. Only call this once.
345820
def _get_stdout_stderr_streams(self):
        """"""
        if six.PY2 or not hasattr(sys.stdout, "buffer"):
            if hasattr(sys.stdout, "fileno") and sys.stdout.isatty():
                try:
                    stdout = os.fdopen(sys.stdout.fileno(), "w+", 0)
                    stderr = os.fdopen(sys.stderr.fileno(), "w+", 0)
                # OSError [Errno 22] Invalid argument wandb
                except OSError:
                    stdout = sys.stdout
                    stderr = sys.stderr
            else:
                stdout = sys.stdout
                stderr = sys.stderr
        else:  # we write binary so grab the raw I/O objects in python 3
            try:
                stdout = sys.stdout.buffer.raw
                stderr = sys.stderr.buffer.raw
            except AttributeError:
                # The testing environment and potentially others may have screwed with their
                # io so we fallback to raw stdout / err
                stdout = sys.stdout.buffer
                stderr = sys.stderr.buffer

        output_log_path = os.path.join(self._run.dir, OUTPUT_FNAME)
        self._output_log = WriteSerializingFile(open(output_log_path, 'wb'))

        stdout_streams = [stdout, self._output_log]
        stderr_streams = [stderr, self._output_log]

        if self._cloud:
            # Tee stdout/stderr into our TextOutputStream, which will push lines to the cloud.
            fs_api = self._api.get_file_stream_api()
            self._stdout_stream = streaming_log.TextStreamPusher(
                fs_api, OUTPUT_FNAME, prepend_timestamp=True)
            self._stderr_stream = streaming_log.TextStreamPusher(
                fs_api, OUTPUT_FNAME, line_prepend='ERROR',
                prepend_timestamp=True)

            stdout_streams.append(self._stdout_stream)
            stderr_streams.append(self._stderr_stream)

        return stdout_streams, stderr_streams
1270115
def setup_stream_handlers(conf):
    """"""
    class StdoutFilter(logging.Filter):
        def filter(self, record):
            return record.levelno in (logging.DEBUG, logging.INFO)

    log.handlers = []

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.WARNING)
    stdout_handler.addFilter(StdoutFilter())
    if conf.debug:
        stdout_handler.setLevel(logging.DEBUG)
    elif conf.verbose:
        stdout_handler.setLevel(logging.INFO)
    else:
        stdout_handler.setLevel(logging.WARNING)
    log.addHandler(stdout_handler)

    stderr_handler = logging.StreamHandler(sys.stderr)
    msg_format = "%(levelname)s: %(message)s"
    stderr_handler.setFormatter(logging.Formatter(fmt=msg_format))
    stderr_handler.setLevel(logging.WARNING)
    log.addHandler(stderr_handler)
244075
def set_stream_color(stream, disabled):
    
    original_stdout = sys.stdout
    original_stderr = sys.stderr

    init(strip=disabled)

    if stream != original_stdout:
        sys.stdout = original_stdout
        sys.stderr = BinaryStreamWrapper(stream, sys.stderr)
    if stream != original_stderr:
        sys.stderr = original_stderr
        sys.stdout = BinaryStreamWrapper(stream, sys.stdout)
212334
def flush():
    """"""
    try:
        sys.stdout.flush()
        sys.stderr.flush()
    except (AttributeError, ValueError, IOError):
        pass  # unsupported
    try:
        libc.fflush(None)
    except (AttributeError, ValueError, IOError):
        pass
1030813
public static StderrStream create()
  {
    if (_stderr == null) {
      _stderr = new StderrStream();
      ConstPath path = new ConstPath(null, _stderr);
      path.setScheme("stderr");
      //_stderr.setPath(path);
    }

    return _stderr;
  }
694290
public static StdoutStream create()
  {
    if (_stdout == null) {
      _stdout = new StdoutStream();
      ConstPath path = new ConstPath(null, _stdout);
      path.setScheme("stdout");
      //_stdout.setPath(path);
    }

    return _stdout;
  }
1219472
def attach_log_stream(self):
        
        if self.has_api_logs:
            self.log_stream = self.attach(stdout=True, stderr=True, stream=True)
1370286
def configure_stream(level='WARNING'):
    
    # get the root logger
    root_logger = logging.getLogger()
    # set the logger level to the same as will be used by the handler
    root_logger.setLevel(level)

    # customize formatter, align each column
    template = "[%(asctime)s] %(name)-25s %(levelname)-8s %(message)s"
    formatter = logging.Formatter(template)

    # add a basic STDERR handler to the logger
    console = logging.StreamHandler()
    console.setLevel(level)
    console.setFormatter(formatter)

    root_logger.addHandler(console)
    return root_logger
1266986
def start(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
        
        if self.pre_start_check():
            # Some other executor (or process) is running with same config:
            raise AlreadyRunning(self)

        if self.process is None:
            command = self.command
            if not self._shell:
                command = self.command_parts

            env = os.environ.copy()
            env[ENV_UUID] = self._uuid
            popen_kwargs = {
                'shell': self._shell,
                'stdin': subprocess.PIPE,
                'stdout': stdout,
                'stderr': stderr,
                'universal_newlines': True,
                'env': env,
            }
            if platform.system() != 'Windows':
                popen_kwargs['preexec_fn'] = os.setsid
            self.process = subprocess.Popen(
                command,
                **popen_kwargs,
            )

        self._set_timeout()

        self.wait_for(self.check_subprocess)
        return self
458295
private void createProcessOutputPump(InputStream is, OutputStream os) {
        outputThread = createPump(is, os, CLOSE_STDOUT_AND_STDERR_INSTREAMS_WHEN_EXHAUSTED);
    }
108769
def fix_windows_stdout_stderr():
    

    if hasattr(sys, "frozen") and sys.platform == "win32":
        try:
            sys.stdout.write("\n")
            sys.stdout.flush()
        except:
            class DummyStream(object):
                def __init__(self): pass

                def write(self, data): pass

                def read(self, data): pass

                def flush(self): pass

                def close(self): pass

            sys.stdout, sys.stderr, sys.stdin = DummyStream(), DummyStream(), DummyStream()
            sys.__stdout__, sys.__stderr__, sys.__stdin__ = DummyStream(), DummyStream(), DummyStream()
830483
def mirror_stdout_stderr(self):
        """"""
        # TODO: Ideally we could start collecting logs without pushing
        fs_api = self._api.get_file_stream_api()
        io_wrap.SimpleTee(sys.stdout, streaming_log.TextStreamPusher(
            fs_api, OUTPUT_FNAME, prepend_timestamp=True))
        io_wrap.SimpleTee(sys.stderr, streaming_log.TextStreamPusher(
            fs_api, OUTPUT_FNAME, prepend_timestamp=True, line_prepend='ERROR'))
1314092
function stream(out, err) {
  if(!err) err = out;

  if(typeof out === 'string') {
    this._out = fs.createWriteStream(out);
  }else{
    this._out = out;
  }

  if(typeof err === 'string') {
    this._err = fs.createWriteStream(err);
  }else{
    this._err = err;
  }

  if((!(this._out instanceof Writable)
      && this._out !== process.stdout)
    || (!(this._err instanceof Writable)
      && this._err !== process.stderr)) {
    throw new Error('invalid log stream');
  }
}
376348
def _create_stdout_logger():
    
    log = logging.getLogger(__name__)
    out_hdlr = logging.StreamHandler(sys.stdout)
    out_hdlr.setFormatter(logging.Formatter('%(message)s'))
    out_hdlr.setLevel(logging.INFO)
    log.addHandler(out_hdlr)
    log.setLevel(logging.INFO)
1114988
def run(self, instream=sys.stdin):
        
        sys.stdout.write(self.prompt)
        sys.stdout.flush()
        while True:
            line = instream.readline()
            try:
                self.exec_cmd(line)
            except Exception as e:
                self.errfun(e)

            sys.stdout.write(self.prompt)
            sys.stdout.flush()
1100762
def execute!
      exit_code = begin
        # Thor accesses these streams directly rather than letting them be injected, so we replace them...
        $stderr = @stderr
        $stdin = @stdin
        $stdout = @stdout

        # Run our normal Thor app the way we know and love.
        DCMetro::Cli::Application.start(ARGV)

        # Thor::Base#start does not have a return value, assume success if no exception is raised.
        0
      rescue StandardError => e
        # The ruby interpreter would pipe this to STDERR and exit 1 in the case of an unhandled exception
        b = e.backtrace
        @stderr.puts("#{b.shift}: #{e.message} (#{e.class})")
        @stderr.puts(b.map{|s| "\tfrom #{s}"}.join("\n"))
        1
      rescue SystemExit => e
        e.status
      ensure
        # TODO: reset your app here, free up resources, etc.
        # Examples:
        # MyApp.logger.flush
        # MyApp.logger.close
        # MyApp.logger = nil
        #
        # MyApp.reset_singleton_instance_variables

        # ...then we put the streams back.
        $stderr = STDERR
        $stdin = STDIN
        $stdout = STDOUT
      end

      # Proxy our exit code back to the injected kernel.
      @kernel.exit(exit_code)
    end
918806
private void createProcessErrorPump(InputStream is, OutputStream os) {
        errorThread = createPump(is, os, CLOSE_STDOUT_AND_STDERR_INSTREAMS_WHEN_EXHAUSTED);
    }