Search prompt and send command, while process is opened
 @yield [match] Send operations when found prompt
 @yieldparam match [String] Expect matches string (prompt)
351394
def do_on_interactive_process
      until @reader.closed? || @reader.eof?
        @reader.expect(expect_regexp, @timeout) do |match|
          yield match
        end
      end
    rescue Errno::EIO => error
      # on linux, PTY raises Errno::EIO when spawned process closed.
      @logger.debug "PTY raises Errno::EIO, #{error.message}"
    end
1356431
def command?(cmd)
      !!system(cmd, out: ::File::NULL, err: ::File::NULL)
    end
403666
def _send_command(self, cmd, expect=None):
        
        if not self.is_alive:
            raise NotPlayingError()
        logger.debug("Send command to mplayer: " + cmd)
        cmd = cmd + "\n"
        # In Py3k, TypeErrors will be raised because cmd is a string but stdin
        # expects bytes. In Python 2.x on the other hand, UnicodeEncodeErrors
        # will be raised if cmd is unicode. In both cases, encoding the string
        # will fix the problem.
        try:
            self.sub_proc.stdin.write(cmd)
        except (TypeError, UnicodeEncodeError):
            self.sub_proc.stdin.write(cmd.encode('utf-8', 'ignore'))
        time.sleep(0.1)     # wait for mplayer (better idea?)
        # Expect a response for 'get_property' only
        if not expect:
            return
        while True:
            try:
                output = self.sub_proc.stdout.readline().rstrip()
                output = output.decode('utf-8')
            except IOError:
                return None
            # print output
            split_output = output.split('=')
            # print(split_output)
            if len(split_output) == 2 and split_output[0].strip() == expect:
                # We found it
                value = split_output[1]
                return value.strip()
697212
def command_output(command, expect_command = true)  #:doc:
      # get everything except for the ending prompt.
      ret =
          if (prompt_pos = (output =~ prompt_match))
            output[0...prompt_pos]
          else
            output
          end

      if expect_command
        command_regex = command_match(command)

        # Go until we run out of data or we find one of the possible command starts.
        # Note that we EXPECT the command to the first line of the output from the command because we expect the
        # shell to echo it back to us.
        result_cmd,_,result_data = ret.partition("\n")
        until result_data.to_s.strip == '' || result_cmd.strip =~ command_regex
          result_cmd,_,result_data = result_data.partition("\n")
        end

        if result_cmd.nil? || !(result_cmd =~ command_regex)
          STDERR.puts "SHELL WARNING: Failed to match #{command_regex.inspect}."
        end

        result_data
      else
        ret
      end
    end
1268761
def send_command(self, data, read_delay=None):
        """"""
        self._write(data)
        if read_delay:
            time.sleep(read_delay)
        return self._read()
320233
def run(command, *args)
      receive_loop # start the loop

      send_args     args.flatten
      send_env      opts[:env]
      send_dir      opts[:dir]
      send_command  command
      send_stdin    opts[:stdin]

      receive_loop.join
      return nil
    end
1167832
def expect(self, pattern, timeout=-1):
        """"""

        if self.blocking:
            raise RuntimeError('expect can only be used on non-blocking commands.')

        self.subprocess.expect(pattern=pattern, timeout=timeout)
76116
def sys_exec(cmd, expect_err = false)
      Open3.popen3(cmd.to_s) do |stdin, stdout, stderr|
        @in_p = stdin
        @out_p = stdout
        @err_p = stderr

        yield @in_p if block_given?
        @in_p.close

        @out = @out_p.read.strip
        @err = @err_p.read.strip
      end

      puts @err unless expect_err || @err.empty? || !$show_err
      @out
    end
654231
def interact(title, description, prompt, binary, options):
    """"""
    args = [binary]
    p = subprocess.Popen(args=args,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         env=os.environ)
    p.args = args  # TODO: remove after Python 2 deprecation.
    expect(p, [b'OK'])

    title = util.assuan_serialize(title.encode('ascii'))
    write(p, b'SETTITLE ' + title + b'\n')
    expect(p, [b'OK'])

    if description:
        description = util.assuan_serialize(description.encode('ascii'))
        write(p, b'SETDESC ' + description + b'\n')
        expect(p, [b'OK'])

    if prompt:
        prompt = util.assuan_serialize(prompt.encode('ascii'))
        write(p, b'SETPROMPT ' + prompt + b'\n')
        expect(p, [b'OK'])

    log.debug('setting %d options', len(options))
    for opt in options:
        write(p, b'OPTION ' + opt + b'\n')
        expect(p, [b'OK', b'ERR'])

    write(p, b'GETPIN\n')
    pin = expect(p, [b'OK', b'D '], confidential=True)

    p.communicate()  # close stdin and wait for the process to exit
    exit_code = p.wait()
    if exit_code:
        raise subprocess.CalledProcessError(exit_code, binary)

    return pin.decode('ascii').strip()
110316
function prompt(question, isYesDefault) {
  if (typeof isYesDefault !== 'boolean') {
    throw new Error(
      'Provide explicit boolean isYesDefault as second argument.'
    );
  }
  return new Promise(resolve => {
    var rlInterface = rl.createInterface({
      input: process.stdin,
      output: process.stdout,
    });

    var hint = isYesDefault === true ? '[Y/n]' : '[y/N]';
    var message = question + ' ' + hint + '\n';

    rlInterface.question(message, function(answer) {
      rlInterface.close();

      var useDefault = answer.trim().length === 0;
      if (useDefault) {
        return resolve(isYesDefault);
      }

      var isYes = answer.match(/^(yes|y)$/i);
      return resolve(isYes);
    });
  });
}
519166
def prompt(name, default):
    
    value = raw_input('%s [%s]: ' %(name, default))
    if not value:
        value = default
    return value
636995
def run_expect_command(self, cmd, expect_end=None, timeout=3, wait_seconds=2):
        
        shell = self.ssh_session.invoke_shell()
        last_time = int(time.time())

        if not cmd.endswith('\n'):
            cmd += '\n'

        def receive():
            buff = ''
            if expect_end is None:
                buff = shell.recv(9999)
            else:
                while not buff.endswith(expect_end):
                    resp = shell.recv(9999)
                    buff += force_text(resp)
                    now = int(time.time())

                    if now - last_time > timeout:
                        break

            buff = force_text(buff)
            logger.info(buff)
            return buff

        logger.info(cmd)
        shell.send(cmd)
        time.sleep(wait_seconds)
        return receive()
433107
def send_command_return(self, obj, command, *arguments):
        
        return self._perform_command('{}/{}'.format(self.session_url, obj.ref), command, OperReturnType.line_output,
                                     *arguments).json()
842534
def process_command_line(preset_command: nil)
      prompt = preset_command ? ":#{preset_command} " : ':'
      command_line.set_prompt prompt
      cmd, *args = command_line.get_command(prompt: prompt).split(' ')
      if cmd && !cmd.empty? && respond_to?(cmd)
        ret = self.public_send cmd, *args
        clear_command_line
        ret
      end
    rescue Interrupt
      clear_command_line
    end
74737
def _process(self):
        
        buffer = self.key_buffer
        retry = False

        while True:
            if retry:
                retry = False
            else:
                buffer.append((yield))

            # If we have some key presses, check for matches.
            if buffer:
                is_prefix_of_longer_match = self._is_prefix_of_longer_match(buffer)
                matches = self._get_matches(buffer)

                # When eager matches were found, give priority to them and also
                # ignore all the longer matches.
                eager_matches = [m for m in matches if m.eager(self._cli_ref())]

                if eager_matches:
                    matches = eager_matches
                    is_prefix_of_longer_match = False

                # Exact matches found, call handler.
                if not is_prefix_of_longer_match and matches:
                    self._call_handler(matches[-1], key_sequence=buffer[:])
                    del buffer[:]  # Keep reference.

                # No match found.
                elif not is_prefix_of_longer_match and not matches:
                    retry = True
                    found = False

                    # Loop over the input, try longest match first and shift.
                    for i in range(len(buffer), 0, -1):
                        matches = self._get_matches(buffer[:i])
                        if matches:
                            self._call_handler(matches[-1], key_sequence=buffer[:i])
                            del buffer[:i]
                            found = True
                            break

                    if not found:
                        del buffer[:1]
930399
def execute(self, command):
        '''
        
        '''
        process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
        while True:
            if process.poll() is not None:
                self.returncode = process.returncode  # pylint: disable=W0201
                break
            yield process.stdout.readline()
1224079
def begin_stream(self, command: Command) -> Reply:
        '''
        '''
        yield from self._control_stream.write_command(command)
        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match(
            'Begin stream',
            (
                ReplyCodes.file_status_okay_about_to_open_data_connection,
                ReplyCodes.data_connection_already_open_transfer_starting,
            ),
            reply
        )

        return reply