Connect stdin/stdout to controlling terminal even if the scripts input and output
    were redirected. This is useful in utilities based on termenu.
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
964409
def fork_exec(args, stdin='', **kwargs):
    

    as_bytes = isinstance(stdin, bytes)
    source = stdin if as_bytes else stdin.encode(locale)
    p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
    stdout, stderr = p.communicate(source)
    if as_bytes:
        return stdout, stderr
    return (stdout.decode(locale), stderr.decode(locale))
596761
async def run_script(self, script):
        """"""
        script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep
        self.proc.stdin.write(script.encode('utf-8'))
        await self.proc.stdin.drain()
        self.proc.stdin.close()
672930
def call_out(command):
  
  # start external command process
  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

  # get outputs
  out, _ = p.communicate()

  return p.returncode, out.strip()
26409
def stdout_redirector():
    
    old_stdout = sys.stdout
    sys.stdout = Stream()
    try:
        yield sys.stdout
    finally:
        sys.stdout.close()
        sys.stdout = old_stdout
496857
def Shell(device, *command):
    
    if command:
        return device.StreamingShell(' '.join(command))
    else:
        # Retrieve the initial terminal prompt to use as a delimiter for future reads
        terminal_prompt = device.InteractiveShell()
        print(terminal_prompt.decode('utf-8'))

        # Accept user input in a loop and write that into the interactive shells stdin, then print output
        while True:
            cmd = input('> ')
            if not cmd:
                continue
            elif cmd == 'exit':
                break
            else:
                stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
                if stdout:
                    if isinstance(stdout, bytes):
                        stdout = stdout.decode('utf-8')
                        print(stdout)

        device.Close()
459298
def loop_input(self, on_quit=None):
        
        # Start the init script
        self._run_script(
            self.__session, self._context.get_property(PROP_INIT_FILE)
        )

        # Run the script
        script_file = self._context.get_property(PROP_RUN_FILE)
        if script_file:
            self._run_script(self.__session, script_file)
        else:
            # No script: run the main loop (blocking)
            self._run_loop(self.__session)

        # Nothing more to do
        self._stop_event.set()
        sys.stdout.write("Bye !\n")
        sys.stdout.flush()
        if on_quit is not None:
            # Call a handler if needed
            on_quit()
704637
def file_or_stdin() -> Callable:
    

    def parse(path):
        if path is None or path == "-":
            return sys.stdin
        else:
            return data_io.smart_open(path)

    return parse
446781
def call_output(cmd, stdin=None, encoding_errors="replace", **kwargs):
    """"""
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
    stdout, stderr, retcode = [], [], None
    while retcode is None:
        if stdin is not None:
            logger.log_prefix("<0 ", stdin.rstrip())
        raw_out, raw_err = p.communicate(stdin)
        stdin = None

        out = raw_out.decode(get_encoding(sys.stdout), encoding_errors) if raw_out else ""
        if out:
            logger.log_prefix("1> ", out.rstrip())
        stdout.append(out)

        err = raw_err.decode(get_encoding(sys.stderr), encoding_errors) if raw_err else ""
        if err:
            logger.log_prefix("2> ", err.rstrip())
        stderr.append(err)

        retcode = p.poll()
    return stdout, stderr, retcode
720521
def set_output(self, outfile):
        ''' 
        '''
        if self._orig_stdout:  # restore Usted
            sys.stdout = self._orig_stdout

        self._stream = outfile
        sys.stdout = _LineWriter(self, self._stream, self.default)
90547
def capture_stdout():
    
    stdout = sys.stdout
    sys.stdout = six.moves.cStringIO()
    try:
        yield sys.stdout
    finally:
        sys.stdout = stdout
316854
def get_cmd_output_from_stdin(stdint_content_binary: bytes,
                              *args, encoding: str = SYS_ENCODING) -> str:
    
    p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, stderr = p.communicate(input=stdint_content_binary)
    return stdout.decode(encoding, errors='ignore')
1247768
def run_command(cmd, redirect_output=True, check_exit_code=True):
    
    if redirect_output:
        stdout = subprocess.PIPE
    else:
        stdout = None
    proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
    output = proc.communicate()[0]
    if check_exit_code and proc.returncode != 0:
        raise Exception('Command "%s" failed.\n%s' % (' '.join(cmd), output))
    return output
1183096
function Interface(stdin, stdout, args) {
  var self = this,
      child;

  this.stdin = stdin;
  this.stdout = stdout;
  this.args = args;

  // Two eval modes are available: controlEval and debugEval
  // But controlEval is used by default
  var opts = {
    prompt: 'debug> ',
    input: this.stdin,
    output: this.stdout,
    eval: this.controlEval.bind(this),
    useGlobal: false,
    ignoreUndefined: true
  };
  if (parseInt(process.env['NODE_NO_READLINE'], 10)) {
    opts.terminal = false;
  } else if (parseInt(process.env['NODE_FORCE_READLINE'], 10)) {
    opts.terminal = true;

    // Emulate Ctrl+C if we're emulating terminal
    if (!this.stdout.isTTY) {
      process.on('SIGINT', function() {
        self.repl.rli.emit('SIGINT');
      });
    }
  }
  if (parseInt(process.env['NODE_DISABLE_COLORS'], 10)) {
    opts.useColors = false;
  }
  this.repl = repl.start(opts);

  // Do not print useless warning
  repl._builtinLibs.splice(repl._builtinLibs.indexOf('repl'), 1);

  // Kill child process when main process dies
  this.repl.on('exit', function() {
    process.exit(0);
  });

  // Handle all possible exits
  process.on('exit', this.killChild.bind(this));
  process.once('SIGTERM', process.exit.bind(process, 0));
  process.once('SIGHUP', process.exit.bind(process, 0));

  var proto = Interface.prototype,
      ignored = ['pause', 'resume', 'exitRepl', 'handleBreak',
                 'requireConnection', 'killChild', 'trySpawn',
                 'controlEval', 'debugEval', 'print', 'childPrint',
                 'clearline'],
      shortcut = {
        'run': 'r',
        'cont': 'c',
        'next': 'n',
        'step': 's',
        'out': 'o',
        'backtrace': 'bt',
        'setBreakpoint': 'sb',
        'clearBreakpoint': 'cb',
        'pause_': 'pause'
      };

  function defineProperty(key, protoKey) {
    // Check arity
    var fn = proto[protoKey].bind(self);

    if (proto[protoKey].length === 0) {
      Object.defineProperty(self.repl.context, key, {
        get: fn,
        enumerable: true,
        configurable: false
      });
    } else {
      self.repl.context[key] = fn;
    }
  };

  // Copy all prototype methods in repl context
  // Setup them as getters if possible
  for (var i in proto) {
    if (Object.prototype.hasOwnProperty.call(proto, i) &&
        ignored.indexOf(i) === -1) {
      defineProperty(i, i);
      if (shortcut[i]) defineProperty(shortcut[i], i);
    }
  }

  this.killed = false;
  this.waiting = null;
  this.paused = 0;
  this.context = this.repl.context;
  this.history = {
    debug: [],
    control: []
  };
  this.breakpoints = [];
  this._watchers = [];

  // Run script automatically
  this.pause();

  // XXX Need to figure out why we need this delay
  setTimeout(function() {

    self.run(function() {
      self.resume();
    });
  }, 10);
}
1085239
def supervisor_events(stdin, stdout):
    

    while True:
        stdout.write('READY\n')
        stdout.flush()

        line = stdin.readline()
        headers = get_headers(line)

        payload = stdin.read(int(headers['len']))
        event_headers, event_data = eventdata(payload)

        yield event_headers, event_data

        stdout.write('RESULT 2\nOK')
        stdout.flush()
898865
def pseudo_raw_input(self, prompt: str) -> str:
        
        if self.use_rawinput:
            try:
                if sys.stdin.isatty():
                    # Wrap in try since terminal_lock may not be locked when this function is called from unit tests
                    try:
                        # A prompt is about to be drawn. Allow asynchronous changes to the terminal.
                        self.terminal_lock.release()
                    except RuntimeError:
                        pass

                    # Deal with the vagaries of readline and ANSI escape codes
                    safe_prompt = rl_make_safe_prompt(prompt)
                    line = input(safe_prompt)
                else:
                    line = input()
                    if self.echo:
                        sys.stdout.write('{}{}\n'.format(prompt, line))
            except EOFError:
                line = 'eof'
            finally:
                if sys.stdin.isatty():
                    # The prompt is gone. Do not allow asynchronous changes to the terminal.
                    self.terminal_lock.acquire()
        else:
            if self.stdin.isatty():
                # on a tty, print the prompt first, then read the line
                self.poutput(prompt, end='')
                self.stdout.flush()
                line = self.stdin.readline()
                if len(line) == 0:
                    line = 'eof'
            else:
                # we are reading from a pipe, read the line to see if there is
                # anything there, if so, then decide whether to print the
                # prompt or not
                line = self.stdin.readline()
                if len(line):
                    # we read something, output the prompt and the something
                    if self.echo:
                        self.poutput('{}{}'.format(prompt, line))
                else:
                    line = 'eof'

        return line.strip()
1357500
async def run_script(self, script):
        """"""
        # Create a Bash command to add all the tools to PATH.
        tools_paths = ':'.join([map_["dest"] for map_ in self.tools_volumes])
        add_tools_path = 'export PATH=$PATH:{}'.format(tools_paths)
        # Spawn another child bash, to avoid running anything as PID 1, which has special
        # signal handling (e.g., cannot be SIGKILL-ed from inside).
        # A login Bash shell is needed to source /etc/profile.
        bash_line = '/bin/bash --login; exit $?' + os.linesep
        script = os.linesep.join(['set -x', 'set +B', add_tools_path, script]) + os.linesep
        self.proc.stdin.write(bash_line.encode('utf-8'))
        await self.proc.stdin.drain()
        self.proc.stdin.write(script.encode('utf-8'))
        await self.proc.stdin.drain()
        self.proc.stdin.close()