Strip out command echo, trailing router prompt and ANSI escape codes.

        :param output: Output from a remote network device
        :type output: unicode string

        :param strip_command:
        :type strip_command:
428402
def _sanitize_output(
        self, output, strip_command=False, command_string=None, strip_prompt=False
    ):
        
        if self.ansi_escape_codes:
            output = self.strip_ansi_escape_codes(output)
        output = self.normalize_linefeeds(output)
        if strip_command and command_string:
            command_string = self.normalize_linefeeds(command_string)
            output = self.strip_command(command_string, output)
        if strip_prompt:
            output = self.strip_prompt(output)
        return output
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()
997668
def strip_from_ansi_esc_sequences(text):
    
    # esc[ + values + control character
    # h, l, p commands are complicated, let's ignore them
    seq_regex = r"\x1b\[[0-9;]*[mKJusDCBAfH]"
    regex = re.compile(seq_regex)
    start = 0
    response = ""
    for match in regex.finditer(text):
        end = match.start()
        response += text[start:end]

        start = match.end()
    response += text[start:len(text)]
    return response
779493
def strip_prompt(self, a_string):
        
        response_list = a_string.split(self.RESPONSE_RETURN)
        last_line = response_list[-1]
        if self.base_prompt in last_line:
            return self.RESPONSE_RETURN.join(response_list[:-1])
        else:
            return a_string
1083866
def get_external_command_output(command: str) -> bytes:
    
    args = shlex.split(command)
    ret = subprocess.check_output(args)  # this needs Python 2.7 or higher
    return ret
286872
def get_exit_code #:nodoc:
      cmd = options[:override_get_exit_code] || 'echo $?'
      if cmd.respond_to?(:call)
        cmd.call(self)
      else
        debug 'Retrieving exit code from last command...'
        discard_local_buffer do
          send_data cmd + line_ending
          wait_for_prompt 1, 2
          ret = command_output(cmd).strip.to_i
        end
        debug 'Exit code: ' + ret.to_s
        ret
      end
    end
602666
def cmd_output(self, args):
        ''''''
        if len(args) < 1 or args[0] == "list":
            self.cmd_output_list()
        elif args[0] == "add":
            if len(args) != 2:
                print("Usage: output add OUTPUT")
                return
            self.cmd_output_add(args[1:])
        elif args[0] == "remove":
            if len(args) != 2:
                print("Usage: output remove OUTPUT")
                return
            self.cmd_output_remove(args[1:])
        elif args[0] == "sysid":
            if len(args) != 3:
                print("Usage: output sysid SYSID OUTPUT")
                return
            self.cmd_output_sysid(args[1:])
        else:
            print("usage: output <list|add|remove|sysid>")
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
153578
def strip_prompt(self, a_string):
        """"""
        response_list = a_string.split(self.RESPONSE_RETURN)
        new_response_list = []
        for line in response_list:
            if self.base_prompt not in line:
                new_response_list.append(line)

        output = self.RESPONSE_RETURN.join(new_response_list)
        return self.strip_context_items(output)
298854
def tee2(process, filter):
    
    while True:
        line = process.stderr.readline()
        if line:
            if sys.version_info[0] >= 3:
                line = decode(line)
            stripped_line = line.rstrip()
            if filter(stripped_line):
                sys.stderr.write(line)
        elif process.returncode is not None:
            process.stderr.close()
            break
194884
def format_command(
    command_args,  # type: List[str]
    command_output,  # type: str
):
    # type: (...) -> str
    
    text = 'Command arguments: {}\n'.format(command_args)

    if not command_output:
        text += 'Command output: None'
    elif logger.getEffectiveLevel() > logging.DEBUG:
        text += 'Command output: [use --verbose to show]'
    else:
        if not command_output.endswith('\n'):
            command_output += '\n'
        text += (
            'Command output:\n{}'
            '-----------------------------------------'
        ).format(command_output)

    return text
28958
def get_simple_output(self, stderr=STDOUT):
        
        args = shlex.split(self.cmd)
        proc = Popen(args, stdout=PIPE, stderr=stderr)
        return proc.communicate()[0].decode("utf8")
298943
def _parse_show_output(cmd_ret):
    '''
    
    '''
    parsed_data = dict()
    list_key = None

    for line in cmd_ret.splitlines():
        # Skip empty lines.
        if not line.strip():
            continue

        # If there are indented lines below an existing key, assign them as a list value
        # for that key.
        if not salt.utils.stringutils.contains_whitespace(line[0]):
            list_key = None

        if list_key:
            list_value = _convert_to_closest_type(line)
            parsed_data.setdefault(list_key, []).append(list_value)
            continue

        items = [item.strip() for item in line.split(':', 1)]

        key = items[0].lower()
        key = ' '.join(key.split()).replace(' ', '_')

        # Track the current key so that we can use it in instances where the values
        # appear on subsequent lines of the output.
        list_key = key

        try:
            value = items[1]
        except IndexError:
            # If the line doesn't have the separator or is otherwise invalid, skip it.
            log.debug('Skipping line: %s', line)
            continue

        if value:
            parsed_data[key] = _convert_to_closest_type(value)

    return _convert_parsed_show_output(parsed_data=parsed_data)
90669
def get_output(cls, response: requests.Response) -> str:
        
        output = response.headers['X-Lizzy-Output']  # type: str
        output = output.replace('\\n', '\n')  # unescape new lines
        lines = ('[AGENT] {}'.format(line) for line in output.splitlines())
        return '\n'.join(lines)
986199
def strip(self, chars=None):
        
        return self.__class__(
            self._str_strip('strip', chars),
            no_closing=chars and (closing_code in chars),
        )
1131526
def string_format(data, out, opts=None, **kwargs):
    '''
    
    '''
    raw_output = try_printout(data, out, opts, **kwargs)
    ansi_escape = re.compile(r'\x1b[^m]*m')
    return ansi_escape.sub('', raw_output)
331970
def stderr_output(cmd):
    """"""

    handle, gpg_stderr = stderr_handle()
    try:
        output = subprocess.check_output(cmd, stderr=gpg_stderr)  # nosec
        if handle:
            handle.close()

        return str(polite_string(output))
    except subprocess.CalledProcessError as exception:
        LOGGER.debug("GPG Command %s", ' '.join(exception.cmd))
        LOGGER.debug("GPG Output %s", exception.output)
        raise CryptoritoError('GPG Execution')