예제 #1
0
  def find(self, image_file):
    '''More useful - find the best format handler in the registry for your
    image file. N.B. this is in principle a factory function.'''

    self.setup()

    # Recursively check whether any of the children understand
    # image_file, in which case they are preferred over the parent
    # format.
    def recurse(format, image_file):
      for child in sorted(format._children, key=lambda x: x.__name__):
        try:
          if child.understand(image_file):
            return recurse(child, image_file)
        except Exception:
          pass
      return format

    for format in sorted(self._formats, key=lambda x: x.__name__):
      try:
        if format.understand(image_file):
          return recurse(format, image_file)
      except Exception:
        pass

    # Try opening the file; this could be an easy reason for failure
    if not Format.is_url(image_file):
      try:
        with open(image_file) as f:
          pass
      except IOError as e:
        # Assume that the OS file error makes sense to the user
        raise SorryIOError(e)

    raise IOError('no format support found for %s' % image_file)