Created
January 25, 2019 11:27
-
-
Save tomasn4a/c413c2ebcf26dfc90dcef8fddde74f34 to your computer and use it in GitHub Desktop.
Modified skimage io util to prevent bug when trying to read a remote image with a long querystring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try: | |
import urllib.parse # Python 3 | |
except ImportError: | |
from urllib2 import urlopen # Python 2 | |
import os | |
import re | |
import tempfile | |
from contextlib import contextmanager | |
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): | |
url_components = urllib.parse.urlparse(resource_name) | |
_, ext = os.path.splitext(url_components.path) | |
try: | |
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as f: | |
u = urllib.request.urlopen(resource_name) | |
f.write(u.read()) | |
# f must be closed before yielding | |
yield f.name | |
finally: | |
os.remove(f.name) | |
else: | |
yield resource_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment