From 86abc7c9704b75242f51392189b1d33afec34041 Mon Sep 17 00:00:00 2001 From: Tony S Yu Date: Tue, 3 Dec 2013 22:16:09 -0600 Subject: [PATCH] Factor out url handling for unified file/url behavior --- skimage/io/_io.py | 29 +++-------------------------- skimage/io/util.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 26 deletions(-) create mode 100644 skimage/io/util.py diff --git a/skimage/io/_io.py b/skimage/io/_io.py index aa342c33..ce718742 100644 --- a/skimage/io/_io.py +++ b/skimage/io/_io.py @@ -1,11 +1,3 @@ -try: - from urllib.request import urlopen # Python 3 -except ImportError: - from urllib2 import urlopen # Python 2 - -import os -import re -import tempfile from io import BytesIO import numpy as np @@ -13,21 +5,13 @@ import six from skimage.io._plugins import call_plugin from skimage.color import rgb2grey - +from skimage._shared import six +from .util import file_or_url_context __all__ = ['Image', 'imread', 'imread_collection', 'imsave', 'imshow', 'show'] -URL_REGEX = re.compile(r'http://|https://|ftp://|file://|file:\\') - - -def is_url(filename): - """Return True if string is an http or ftp path.""" - return (isinstance(filename, six.string_types) and - URL_REGEX.match(filename) is not None) - - class Image(np.ndarray): """Class representing Image data. @@ -110,14 +94,7 @@ def imread(fname, as_grey=False, plugin=None, flatten=None, if flatten is not None: as_grey = flatten - if is_url(fname): - _, ext = os.path.splitext(fname) - with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as f: - u = urlopen(fname) - f.write(u.read()) - img = call_plugin('imread', f.name, plugin=plugin, **plugin_args) - os.remove(f.name) - else: + with file_or_url_context(fname) as fname: img = call_plugin('imread', fname, plugin=plugin, **plugin_args) if as_grey and getattr(img, 'ndim', 0) >= 3: diff --git a/skimage/io/util.py b/skimage/io/util.py new file mode 100644 index 00000000..06f5a5b5 --- /dev/null +++ b/skimage/io/util.py @@ -0,0 +1,36 @@ +try: + from urllib.request import urlopen # Python 3 +except ImportError: + from urllib2 import urlopen # Python 2 + +import os +import re +import tempfile +from contextlib import contextmanager + +from skimage._shared import six + + +URL_REGEX = re.compile(r'http://|https://|ftp://|file://|file:\\') + + +def is_url(filename): + """Return True if string is an http or ftp path.""" + return (isinstance(filename, six.string_types) and + URL_REGEX.match(filename) is not None) + + +@contextmanager +def file_or_url_context(resource_name): + """Yield name of file from the given resource (i.e. file or url).""" + if is_url(resource_name): + _, ext = os.path.splitext(resource_name) + with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as f: + u = urlopen(resource_name) + f.write(u.read()) + try: + yield f.name + finally: + os.remove(f.name) + else: + yield resource_name