call check_output command to read content from a file
761100
def check_output_command(file_path, head=None, tail=None):
    ''''''
    if os.path.exists(file_path):
        if sys.platform == 'win32':
            cmds = ['powershell.exe', 'type', file_path]
            if head:
                cmds += ['|', 'select', '-first', str(head)]
            elif tail:
                cmds += ['|', 'select', '-last', str(tail)]
            return check_output(cmds, shell=True).decode('utf-8')
        else:
            cmds = ['cat', file_path]
            if head:
                cmds = ['head', '-' + str(head), file_path]
            elif tail:
                cmds = ['tail', '-' + str(tail), file_path]
            return check_output(cmds, shell=False).decode('utf-8')
    else:
        print_error('{0} does not exist!'.format(file_path))
        exit(1)
700999
def Read(cls, usb, expected_cmds, timeout_ms=None, total_timeout_ms=None):
        """"""
        total_timeout_ms = usb.Timeout(total_timeout_ms)
        start = time.time()
        while True:
            msg = usb.BulkRead(24, timeout_ms)
            cmd, arg0, arg1, data_length, data_checksum = cls.Unpack(msg)
            command = cls.constants.get(cmd)
            if not command:
                raise InvalidCommandError(
                    'Unknown command: %x' % cmd, cmd, (arg0, arg1))
            if command in expected_cmds:
                break

            if time.time() - start > total_timeout_ms:
                raise InvalidCommandError(
                    'Never got one of the expected responses (%s)' % expected_cmds,
                    cmd, (timeout_ms, total_timeout_ms))

        if data_length > 0:
            data = bytearray()
            while data_length > 0:
                temp = usb.BulkRead(data_length, timeout_ms)
                if len(temp) != data_length:
                    print(
                        "Data_length {} does not match actual number of bytes read: {}".format(data_length, len(temp)))
                data += temp

                data_length -= len(temp)

            actual_checksum = cls.CalculateChecksum(data)
            if actual_checksum != data_checksum:
                raise InvalidChecksumError(
                    'Received checksum %s != %s', (actual_checksum, data_checksum))
        else:
            data = b''
        return command, arg0, arg1, bytes(data)
740892
def execute(cmd):
  '''  '''
  try:
    return safely_decode(check_output(cmd))
  except Exception as e:
    logger.warn(u'Couldnt execute cmd: %s.\nReason: %s' % (cmd, e))
    return None
82416
def execute_get_text(command, raise_errors=False):  # type: (str, bool) -> str
    
    try:
        result = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
        # print(result.decode())
    except subprocess.CalledProcessError:
        if raise_errors:
            raise
        return ""
    if result:
        return result.decode("utf-8")
    return ""
947711
def get_output(self, output_files, clear=True):
        ""
        patt = re.compile(r'(.*?)-semantics.*?')
        for outpath in output_files:
            if outpath is None:
                logger.warning("Found outpath with value None. Skipping.")
                continue

            re_out = patt.match(path.basename(outpath))
            if re_out is None:
                raise SparserError("Could not get prefix from output path %s."
                                   % outpath)
            prefix = re_out.groups()[0]
            if prefix.startswith('PMC'):
                prefix = prefix[3:]
            if prefix.isdecimal():
                # In this case we assume the prefix is a tcid.
                prefix = int(prefix)

            try:
                with open(outpath, 'rt') as f:
                    content = json.load(f)
            except Exception as e:
                logger.exception(e)
                logger.error("Could not load reading content from %s."
                             % outpath)
                content = None

            self.add_result(prefix, content)

            if clear:
                input_path = outpath.replace('-semantics.json', '.nxml')
                try:
                    remove(outpath)
                    remove(input_path)
                except Exception as e:
                    logger.exception(e)
                    logger.error("Could not remove sparser files %s and %s."
                                 % (outpath, input_path))
        return self.results
788515
def get_output(cmd, args):
    
    from subprocess import Popen, STDOUT, PIPE

    command = [cmd]
    command.extend(listify(args))

    process = Popen(command, stdout=PIPE, stderr=STDOUT)
    out, _ = process.communicate()

    return out.decode('utf-8')
737913
def output(data, stream_name = :stdout, &block)
        # Pass the output to the block
        if block.arity == 2
          args = [nil, nil]
          if stream_name == :stdout
            args[0] = data
          else
            args[1] = data
          end
          block.call(*args)
        else
          yield data if stream_name == :stdout
        end
      end
1350293
def show_output(self, txt, device='Console'):
        
        if device == 'Console':
            print(txt)
        elif device == 'File':
            raise ('show_output to File not implemented')
        elif device == 'Function_Return':  # hacky, to run test_AI_CLI.py
            return txt
721801
def run(command, get_output=False, cwd=None):
    
    if cwd is None:
        cwd = GITPATH

    cprint('===')
    cprint('===  Command: ', command)
    cprint('===  CWD:     ', cwd)
    cprint('===')

    if get_output:
        proc = capture_stdout(command, cwd=cwd)
        out = proc.stdout.read().decode()
        print(out, end='')
        check_exit_code(proc.returncode)
        return out
    else:
        proc = sarge_run(command, cwd=cwd)
        check_exit_code(proc.returncode)
368437
def display_output(data, out=None, opts=None, **kwargs):
    '''
    
    '''
    if opts is None:
        opts = {}
    display_data = try_printout(data, out, opts, **kwargs)

    output_filename = opts.get('output_file', None)
    log.trace('data = %s', data)
    try:
        # output filename can be either '' or None
        if output_filename:
            if not hasattr(output_filename, 'write'):
                ofh = salt.utils.files.fopen(output_filename, 'a')  # pylint: disable=resource-leakage
                fh_opened = True
            else:
                # Filehandle/file-like object
                ofh = output_filename
                fh_opened = False

            try:
                fdata = display_data
                if isinstance(fdata, six.text_type):
                    try:
                        fdata = fdata.encode('utf-8')
                    except (UnicodeDecodeError, UnicodeEncodeError):
                        # try to let the stream write
                        # even if we didn't encode it
                        pass
                if fdata:
                    ofh.write(salt.utils.stringutils.to_str(fdata))
                    ofh.write('\n')
            finally:
                if fh_opened:
                    ofh.close()
            return
        if display_data:
            salt.utils.stringutils.print_cli(display_data)
    except IOError as exc:
        # Only raise if it's NOT a broken pipe
        if exc.errno != errno.EPIPE:
            raise exc
651567
def process
      @command = "#{WebifyRuby.webify_binary} #{Shellwords.escape(@file)}"
      @output = Open3.popen3(@command) { |stdin, stdout, stderr| stdout.read }

      if not is_valid?
        WebifyRuby.logger.fatal "Invalid input received\n@command\n#{@command}\n@output\n#{@output}\n"
        raise Error, "Binary responded with failure:\n#{@output}"
      end

      @generated = Shellwords.escape(@output).split("'\n'").select{|s| s.match('Generating')}.join().split('Generating\\ ')[1..-1]

      if @generated.to_a.empty?
        WebifyRuby.logger.info "No file output received\n@command\n#{@command}\n@output\n#{@output}\n"
      end
    end
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
702119
def print
      return unless $stdout.tty?
      return if recently_fetched?

      resp = fetch_server_message
      update_fetched
      puts resp unless resp.empty?
    end
752426
def execute_get_text(command):  # type: (str) ->str
    
    try:
        _ = subprocess.run
        try:
            completed = subprocess.run(
                command,
                check=True,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
        except subprocess.CalledProcessError as cpe:
            raise
        else:
            return completed.stdout.decode('utf-8') + completed.stderr.decode("utf-8")
    except AttributeError:
        try:
            p = subprocess.Popen(command.split(" "), stdout=subprocess.PIPE)
            out, err = p.communicate()
        except subprocess.CalledProcessError as cpe:
            raise
        else:
            return str(out) + str(err)
455821
def _check_output(self, command):
        """"""
        try:
            if sys.version_info[0] > 2:
                return check_output(self.base_command + command, stderr=STDOUT).decode('utf8')
            else:
                return check_output(self.base_command + command, stderr=STDOUT)
        except CalledProcessError as command_error:
            raise GitCommandException(*command_error.args)
298935
def _check_file(self, filename):
    
    # If the user specifies an invalid severity use comment.
    log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT)

    failure_count = 0
    fail_threshold = Nit.WARNING if self._strict else Nit.ERROR

    for i, nit in enumerate(self._get_nits(filename)):
      if i == 0:
        print()  # Add an extra newline to clean up the output only if we have nits.
      if nit.severity >= log_threshold:
        print('{nit}\n'.format(nit=nit))
      if nit.severity >= fail_threshold:
        failure_count += 1
    return failure_count
1156669
def read(self, source, compressed=False, encoding='UTF-8'):
        
        buf = ''
        for block in self.cat(source, compressed=compressed, encoding=encoding):
            buf += block
            if '\n' in buf:
                ret, buf = buf.rsplit('\n', 1)
                for line in ret.split('\n'):
                    yield line

        lines = buf.split('\n')
        for line in lines[:-1]:
            yield line

        # only yield the last line if the line has content in it
        if lines[-1]:
            yield lines[-1]