Exemplo n.º 1
0
    def _display(self, ind=0):
        """
        Print out nested structure with corresponding indentations.
        """

        result = []
        element = 0

        # go through the list twice, first time print out all top level
        # messages
        for item in self:
            if not isinstance(item, _ErrList):
                result.append('%s\n' % indent(item, shift=ind))

        # second time go through the next level items, each of the next level
        # must present, even it has nothing.
        for item in self:
            if isinstance(item, _ErrList):
                tmp = item._display(ind=ind + 1)

                # print out a message only if there is something
                if tmp.strip():
                    if self.unit:
                        result.append(indent('%s %s:\n' % (self.unit, element),
                                      shift=ind))
                    result.append(tmp)
                element += 1

        return ''.join(result)
Exemplo n.º 2
0
Arquivo: diff.py Projeto: coleb/PyFITS
def report_diff_values(fileobj, a, b, ind=0):
    """Write a diff between two values to the specified file-like object."""

    if isinstance(a, float):
        a = repr(a)

    if isinstance(b, float):
        b = repr(b)

    if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
        diff_indices = np.where(a != b)
        num_diffs = reduce(lambda x, y: x * y,
                           (len(d) for d in diff_indices), 1)
        for idx in islice(izip(*diff_indices), 3):
            fileobj.write(indent('  at %r:\n' % list(idx), ind))
            report_diff_values(fileobj, a[idx], b[idx], ind=ind + 1)

        if num_diffs:
            fileobj.write(indent('  ...and at %d more indices.\n' %
                          (num_diffs - 3), ind))
        return

    for line in difflib.ndiff(str(a).splitlines(), str(b).splitlines()):
        if line[0] == '-':
            line = 'a>' + line[1:]
        elif line[0] == '+':
            line = 'b>' + line[1:]
        else:
            line = ' ' + line
        fileobj.write(indent('  %s\n' % line.rstrip('\n'), ind))
Exemplo n.º 3
0
Arquivo: diff.py Projeto: coleb/PyFITS
def report_diff_keyword_attr(fileobj, attr, diffs, keyword, ind=0):
    """
    Write a diff between two header keyword values or comments to the specified
    file-like object.
    """

    if keyword in diffs:
        vals = diffs[keyword]
        for idx, val in enumerate(vals):
            if val is None:
                continue
            if idx == 0:
                dup = ''
            else:
                dup = '[%d]' % (idx + 1)
            fileobj.write(indent(' Keyword %-8s%s has different %s:\n' %
                          (keyword, dup, attr), ind))
            report_diff_values(fileobj, val[0], val[1], ind=ind + 1)
Exemplo n.º 4
0
Arquivo: diff.py Projeto: coleb/PyFITS
 def _writeln(self, text):
     self._fileobj.write(indent(text, self._indent) + '\n')
Exemplo n.º 5
0
    def _readfrom(cls, fileobj=None, data=None, mode='readonly',
                  memmap=False, save_backup=False, **kwargs):
        """
        Provides the implementations from HDUList.fromfile and
        HDUList.fromstring, both of which wrap this method, as their
        implementations are largely the same.
        """

        if fileobj is not None:
            # instantiate a FITS file object (ffo)
            ffo = _File(fileobj, mode=mode, memmap=memmap)
            hdulist = cls(file=ffo)
        else:
            hdulist = cls()
            # This method is currently only called from HDUList.fromstring and
            # HDUList.fromfile.  If fileobj is None then this must be the
            # fromstring case; the data type of `data` will be checked in the
            # _BaseHDU.fromstring call.

        hdulist._save_backup = save_backup

        saved_compression_enabled = compressed.COMPRESSION_ENABLED

        try:
            if ('disable_image_compression' in kwargs and
                kwargs['disable_image_compression']):
                compressed.COMPRESSION_ENABLED = False

            if mode == 'ostream':
                # Output stream--not interested in reading/parsing the
                # HDUs--just writing to the output file
                return hdulist

            # read all HDUs
            while True:
                try:
                    if fileobj is not None:
                        try:
                            hdu = _BaseHDU.readfrom(ffo, **kwargs)
                        except EOFError:
                            break
                        except IOError, err:
                            if ffo.writeonly:
                                break
                            else:
                                raise
                    else:
                        if not data:
                            break
                        hdu = _BaseHDU.fromstring(data)
                        data = data[hdu._datLoc + hdu._datSpan:]
                    hdulist.append(hdu)
                    hdu._new = False
                    if 'checksum' in kwargs:
                        hdu._output_checksum = kwargs['checksum']
                # check in the case there is extra space after the last HDU or
                # corrupted HDU
                except (VerifyError, ValueError), err:
                    warnings.warn(
                        'Error validating header for HDU #%d (note: PyFITS '
                        'uses zero-based indexing).\n%s\n'
                        'There may be extra bytes after the last HDU or the '
                        'file is corrupted.' %
                        (len(hdulist), indent(str(err))), VerifyWarning)
                    break