Пример #1
0
def read_inventory(path_or_file_object=None, format=None):
    """
    Function to read inventory files.

    :param path_or_file_object: File name or file like object. If this
        attribute is omitted, an example :class:`Inventory`
        object will be returned.
    :type format: str, optional
    :param format: Format of the file to read (e.g. ``"STATIONXML"``).

    .. note::

        For handling additional information not covered by the
        StationXML standard and how to output it to StationXML
        see the :ref:`ObsPy Tutorial <stationxml-extra>`.
    """
    if path_or_file_object is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_inventory()
    elif isinstance(path_or_file_object, (str, native_str)) and \
            "://" in path_or_file_object:
        # some URL
        # extract extension if any
        suffix = \
            os.path.basename(path_or_file_object).partition('.')[2] or '.tmp'
        with NamedTemporaryFile(suffix=suffix) as fh:
            download_to_file(url=path_or_file_object, filename_or_buffer=fh)
            return read_inventory(fh.name, format=format)
    return _read_from_plugin("inventory", path_or_file_object,
                             format=format)[0]
Пример #2
0
def read_inventory(path_or_file_object=None, format=None):
    """
    Function to read inventory files.

    :param path_or_file_object: File name or file like object. If this
        attribute is omitted, an example :class:`Inventory`
        object will be returned.
    :type format: str, optional
    :param format: Format of the file to read (e.g. ``"STATIONXML"``).

    .. note::

        For handling additional information not covered by the
        StationXML standard and how to output it to StationXML
        see the :ref:`ObsPy Tutorial <stationxml-extra>`.
    """
    if path_or_file_object is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_inventory()
    elif isinstance(path_or_file_object, (str, native_str)) and \
            "://" in path_or_file_object:
        # some URL
        # extract extension if any
        suffix = \
            os.path.basename(path_or_file_object).partition('.')[2] or '.tmp'
        with NamedTemporaryFile(suffix=suffix) as fh:
            download_to_file(url=path_or_file_object, filename_or_buffer=fh)
            return read_inventory(fh.name, format=format)
    return _read_from_plugin("inventory", path_or_file_object,
                             format=format)[0]
Пример #3
0
def read_inventory(path_or_file_object=None, format=None, *args, **kwargs):
    """
    Function to read inventory files.

    :param path_or_file_object: File name or file like object. If this
        attribute is omitted, an example :class:`Inventory`
        object will be returned.
    :type format: str
    :param format: Format of the file to read (e.g. ``"STATIONXML"``). See the
        `Supported Formats`_ section below for a list of supported formats.
    :rtype: :class:`~obspy.core.inventory.inventory.Inventory`
    :return: An ObsPy :class:`~obspy.core.inventory.inventory.Inventory`
        object.

    Additional args and kwargs are passed on to the underlying ``_read_X()``
    methods of the inventory plugins.

    .. rubric:: _`Supported Formats`

    Additional ObsPy modules extend the functionality of the
    :func:`~obspy.core.inventory.inventory.read_inventory` function. The
    following table summarizes all known file formats currently supported by
    ObsPy.

    Please refer to the `Linked Function Call`_ of each module for any extra
    options available at the import stage.

    %s

    .. note::

        For handling additional information not covered by the
        StationXML standard and how to output it to StationXML
        see the :ref:`ObsPy Tutorial <stationxml-extra>`.
    """
    if path_or_file_object is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_inventory()
    elif isinstance(path_or_file_object, (str, native_str)) and \
            "://" in path_or_file_object:
        # some URL
        # extract extension if any
        suffix = \
            os.path.basename(path_or_file_object).partition('.')[2] or '.tmp'
        with NamedTemporaryFile(suffix=sanitize_filename(suffix)) as fh:
            download_to_file(url=path_or_file_object, filename_or_buffer=fh)
            return read_inventory(fh.name, format=format)
    return _read_from_plugin("inventory",
                             path_or_file_object,
                             format=format,
                             *args,
                             **kwargs)[0]
Пример #4
0
def read_inventory(path_or_file_object=None, format=None, *args, **kwargs):
    """
    Function to read inventory files.

    :param path_or_file_object: File name or file like object. If this
        attribute is omitted, an example :class:`Inventory`
        object will be returned.
    :type format: str
    :param format: Format of the file to read (e.g. ``"STATIONXML"``). See the
        `Supported Formats`_ section below for a list of supported formats.
    :rtype: :class:`~obspy.core.inventory.inventory.Inventory`
    :return: An ObsPy :class:`~obspy.core.inventory.inventory.Inventory`
        object.

    Additional args and kwargs are passed on to the underlying ``_read_X()``
    methods of the inventory plugins.

    .. rubric:: _`Supported Formats`

    Additional ObsPy modules extend the functionality of the
    :func:`~obspy.core.inventory.inventory.read_inventory` function. The
    following table summarizes all known file formats currently supported by
    ObsPy.

    Please refer to the `Linked Function Call`_ of each module for any extra
    options available at the import stage.

    %s

    .. note::

        For handling additional information not covered by the
        StationXML standard and how to output it to StationXML
        see the :ref:`ObsPy Tutorial <stationxml-extra>`.
    """
    if path_or_file_object is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_inventory()
    elif isinstance(path_or_file_object, (str, native_str)) and \
            "://" in path_or_file_object:
        # some URL
        # extract extension if any
        suffix = \
            os.path.basename(path_or_file_object).partition('.')[2] or '.tmp'
        with NamedTemporaryFile(suffix=sanitize_filename(suffix)) as fh:
            download_to_file(url=path_or_file_object, filename_or_buffer=fh)
            return read_inventory(fh.name, format=format)
    return _read_from_plugin("inventory", path_or_file_object,
                             format=format, *args, **kwargs)[0]
Пример #5
0
 def test_mock_read_inventory_http_errors(self):
     """
     Tests HTTP Error on 204, 400, and 500
     """
     url = "http://obspy.org"
     for response_tuple in [("204", "No Content"), ("400", "Bad Request"),
                            ("500", "Internal Server Error")]:
         code = response_tuple[0]
         reason = response_tuple[1]
         with mock.patch("requests.get") as mocked_get:
             mocked_get.return_value.status_code = code
             mocked_get.return_value.reason = reason
             msg = "%s HTTP Error: %s for url: %s" % (code, reason, url)
             with pytest.raises(HTTPError, match=msg):
                 download_to_file(url, None)
Пример #6
0
 def test_mock_read_inventory_http_errors(self):
     """
     Tests HTTP Error on 204, 400, and 500
     """
     url = "http://obspy.org"
     for response_tuple in [("204", "No Content"), ("400", "Bad Request"),
                            ("500", "Internal Server Error")]:
         code = response_tuple[0]
         reason = response_tuple[1]
         with mock.patch("requests.get") as mocked_get:
             mocked_get.return_value.status_code = code
             mocked_get.return_value.reason = reason
             with self.assertRaises(HTTPError) as e:
                 download_to_file(url, None)
             self.assertEqual(e.exception.args[0],
                              "%s HTTP Error: %s for url: %s" %
                              (code, reason, url))
Пример #7
0
def read_inventory(path_or_file_object=None, format=None):
    """
    Function to read inventory files.

    :param path_or_file_object: File name or file like object. If this
        attribute is omitted, an example :class:`Inventory`
        object will be returned.
    :type format: str, optional
    :param format: Format of the file to read (e.g. ``"STATIONXML"``).
    """
    if path_or_file_object is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_inventory()
    elif isinstance(path_or_file_object, (str, native_str)) and "://" in path_or_file_object:
        # some URL
        # extract extension if any
        suffix = os.path.basename(path_or_file_object).partition(".")[2] or ".tmp"
        with NamedTemporaryFile(suffix=suffix) as fh:
            download_to_file(url=path_or_file_object, filename_or_buffer=fh)
            return read_inventory(fh.name, format=format)
    return _read_from_plugin("inventory", path_or_file_object, format=format)[0]
Пример #8
0
def read_events(pathname_or_url=None, format=None, **kwargs):
    """
    Read event files into an ObsPy Catalog object.

    The :func:`~obspy.core.event.read_events` function opens either one or
    multiple event files given via file name or URL using the
    ``pathname_or_url`` attribute.

    :type pathname_or_url: str or StringIO.StringIO
    :param pathname_or_url: String containing a file name or a URL or a open
        file-like object. Wildcards are allowed for a file name. If this
        attribute is omitted, an example :class:`~obspy.core.event.Catalog`
        object will be returned.
    :type format: str
    :param format: Format of the file to read (e.g. ``"QUAKEML"``). See the
        `Supported Formats`_ section below for a list of supported formats.
    :rtype: :class:`~obspy.core.event.Catalog`
    :return: An ObsPy :class:`~obspy.core.event.Catalog` object.

    .. rubric:: _`Supported Formats`

    Additional ObsPy modules extend the functionality of the
    :func:`~obspy.core.event.read_events` function. The following table
    summarizes all known file formats currently supported by ObsPy.

    Please refer to the `Linked Function Call`_ of each module for any extra
    options available at the import stage.

    %s

    Next to the :func:`~obspy.core.event.read_events` function the
    :meth:`~obspy.core.event.Catalog.write` method of the returned
    :class:`~obspy.core.event.Catalog` object can be used to export the data to
    the file system.
    """
    if pathname_or_url is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_catalog()
    elif not isinstance(pathname_or_url, (str, native_str)):
        # not a string - we assume a file-like object
        try:
            # first try reading directly
            catalog = _read(pathname_or_url, format, **kwargs)
        except TypeError:
            # if this fails, create a temporary file which is read directly
            # from the file system
            pathname_or_url.seek(0)
            with NamedTemporaryFile() as fh:
                fh.write(pathname_or_url.read())
                catalog = _read(fh.name, format, **kwargs)
        return catalog
    elif isinstance(pathname_or_url, bytes) and \
            pathname_or_url.strip().startswith(b'<'):
        # XML string
        return _read(io.BytesIO(pathname_or_url), format, **kwargs)
    elif "://" in pathname_or_url[:10]:
        # URL
        # extract extension if any
        suffix = os.path.basename(pathname_or_url).partition('.')[2] or '.tmp'
        with NamedTemporaryFile(suffix=sanitize_filename(suffix)) as fh:
            download_to_file(url=pathname_or_url, filename_or_buffer=fh)
            catalog = _read(fh.name, format, **kwargs)
        return catalog
    else:
        pathname = pathname_or_url
        # File name(s)
        pathnames = sorted(glob.glob(pathname))
        if not pathnames:
            # try to give more specific information why the stream is empty
            if glob.has_magic(pathname) and not glob.glob(pathname):
                raise Exception("No file matching file pattern: %s" % pathname)
            elif not glob.has_magic(pathname) and not os.path.isfile(pathname):
                raise IOError(2, "No such file or directory", pathname)

        catalog = _read(pathnames[0], format, **kwargs)
        if len(pathnames) > 1:
            for filename in pathnames[1:]:
                catalog.extend(_read(filename, format, **kwargs).events)
        return catalog
Пример #9
0
def read_events(pathname_or_url=None, format=None, **kwargs):
    """
    Read event files into an ObsPy Catalog object.

    The :func:`~obspy.core.event.read_events` function opens either one or
    multiple event files given via file name or URL using the
    ``pathname_or_url`` attribute.

    :type pathname_or_url: str or StringIO.StringIO
    :param pathname_or_url: String containing a file name or a URL or a open
        file-like object. Wildcards are allowed for a file name. If this
        attribute is omitted, an example :class:`~obspy.core.event.Catalog`
        object will be returned.
    :type format: str
    :param format: Format of the file to read (e.g. ``"QUAKEML"``). See the
        `Supported Formats`_ section below for a list of supported formats.
    :rtype: :class:`~obspy.core.event.Catalog`
    :return: An ObsPy :class:`~obspy.core.event.Catalog` object.

    .. rubric:: _`Supported Formats`

    Additional ObsPy modules extend the functionality of the
    :func:`~obspy.core.event.read_events` function. The following table
    summarizes all known file formats currently supported by ObsPy.

    Please refer to the `Linked Function Call`_ of each module for any extra
    options available at the import stage.

    %s

    Next to the :func:`~obspy.core.event.read_events` function the
    :meth:`~obspy.core.event.Catalog.write` method of the returned
    :class:`~obspy.core.event.Catalog` object can be used to export the data to
    the file system.
    """
    if pathname_or_url is None:
        # if no pathname or URL specified, return example catalog
        return _create_example_catalog()
    elif not isinstance(pathname_or_url, (str, native_str)):
        # not a string - we assume a file-like object
        try:
            # first try reading directly
            catalog = _read(pathname_or_url, format, **kwargs)
        except TypeError:
            # if this fails, create a temporary file which is read directly
            # from the file system
            pathname_or_url.seek(0)
            with NamedTemporaryFile() as fh:
                fh.write(pathname_or_url.read())
                catalog = _read(fh.name, format, **kwargs)
        return catalog
    elif isinstance(pathname_or_url, bytes) and \
            pathname_or_url.strip().startswith(b'<'):
        # XML string
        return _read(io.BytesIO(pathname_or_url), format, **kwargs)
    elif "://" in pathname_or_url[:10]:
        # URL
        # extract extension if any
        suffix = os.path.basename(pathname_or_url).partition('.')[2] or '.tmp'
        with NamedTemporaryFile(suffix=sanitize_filename(suffix)) as fh:
            download_to_file(url=pathname_or_url, filename_or_buffer=fh)
            catalog = _read(fh.name, format, **kwargs)
        return catalog
    else:
        pathname = pathname_or_url
        # File name(s)
        pathnames = sorted(glob.glob(pathname))
        if not pathnames:
            # try to give more specific information why the stream is empty
            if glob.has_magic(pathname) and not glob.glob(pathname):
                raise Exception("No file matching file pattern: %s" % pathname)
            elif not glob.has_magic(pathname) and not os.path.isfile(pathname):
                raise IOError(2, "No such file or directory", pathname)

        catalog = _read(pathnames[0], format, **kwargs)
        if len(pathnames) > 1:
            for filename in pathnames[1:]:
                catalog.extend(_read(filename, format, **kwargs).events)
        return catalog