1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
""" This module contains helper functions for accessing, downloading, and
caching data files.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ..extern import six
from ..extern.six.moves import urllib, range
import atexit
import contextlib
import fnmatch
import hashlib
import os
import io
import shutil
import socket
import sys
import time
from tempfile import NamedTemporaryFile, gettempdir
from warnings import warn
from .. import config as _config
from ..utils.exceptions import AstropyWarning
from ..utils.introspection import find_current_module, resolve_name
try:
import pathlib
except ImportError:
HAS_PATHLIB = False
else:
HAS_PATHLIB = True
__all__ = [
'Conf', 'conf', 'get_readable_fileobj', 'get_file_contents',
'get_pkg_data_fileobj', 'get_pkg_data_filename',
'get_pkg_data_contents', 'get_pkg_data_fileobjs',
'get_pkg_data_filenames', 'compute_hash', 'clear_download_cache',
'CacheMissingWarning', 'get_free_space_in_dir',
'check_free_space_in_dir', 'download_file',
'download_files_in_parallel', 'is_url_in_cache']
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.utils.data`.
"""
dataurl = _config.ConfigItem(
'http://data.astropy.org/',
'URL for astropy remote data site.')
remote_timeout = _config.ConfigItem(
3.,
'Time to wait for remote data queries (in seconds).',
aliases=['astropy.coordinates.name_resolve.name_resolve_timeout'])
compute_hash_block_size = _config.ConfigItem(
2 ** 16, # 64K
'Block size for computing MD5 file hashes.')
download_block_size = _config.ConfigItem(
2 ** 16, # 64K
'Number of bytes of remote data to download per step.')
download_cache_lock_attempts = _config.ConfigItem(
5,
'Number of times to try to get the lock ' +
'while accessing the data cache before giving up.')
delete_temporary_downloads_at_exit = _config.ConfigItem(
True,
'If True, temporary download files created when the cache is '
'inaccessible will be deleted at the end of the python session.')
conf = Conf()
class CacheMissingWarning(AstropyWarning):
"""
This warning indicates the standard cache directory is not accessible, with
the first argument providing the warning message. If args[1] is present, it
is a filename indicating the path to a temporary file that was created to
store a remote data download in the absence of the cache.
"""
def _is_url(string):
"""
Test whether a string is a valid URL
Parameters
----------
string : str
The string to test
"""
url = urllib.parse.urlparse(string)
# we can't just check that url.scheme is not an empty string, because
# file paths in windows would return a non-empty scheme (e.g. e:\\
# returns 'e').
return url.scheme.lower() in ['http', 'https', 'ftp', 'sftp', 'ssh', 'file']
def _is_inside(path, parent_path):
# We have to try realpath too to avoid issues with symlinks, but we leave
# abspath because some systems like debian have the absolute path (with no
# symlinks followed) match, but the real directories in different
# locations, so need to try both cases.
return os.path.abspath(path).startswith(os.path.abspath(parent_path)) \
or os.path.realpath(path).startswith(os.path.realpath(parent_path))
@contextlib.contextmanager
def get_readable_fileobj(name_or_obj, encoding=None, cache=False,
show_progress=True, remote_timeout=None):
"""
Given a filename, pathlib.Path object or a readable file-like object, return a context
manager that yields a readable file-like object.
This supports passing filenames, URLs, and readable file-like objects,
any of which can be compressed in gzip, bzip2 or lzma (xz) if the
appropriate compression libraries are provided by the Python installation.
Notes
-----
This function is a context manager, and should be used for example
as::
with get_readable_fileobj('file.dat') as f:
contents = f.read()
Parameters
----------
name_or_obj : str or file-like object
The filename of the file to access (if given as a string), or
the file-like object to access.
If a file-like object, it must be opened in binary mode.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that on Python 2.x returns `bytes` objects and
on Python 3.x returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
cache : bool, optional
Whether to cache the contents of remote URLs.
show_progress : bool, optional
Whether to display a progress bar if the file is downloaded
from a remote server. Default is `True`.
remote_timeout : float
Timeout for remote requests in seconds (default is the configurable
`astropy.utils.data.Conf.remote_timeout`, which is 3s by default)
Returns
-------
file : readable file-like object
"""
# close_fds is a list of file handles created by this function
# that need to be closed. We don't want to always just close the
# returned file handle, because it may simply be the file handle
# passed in. In that case it is not the responsibility of this
# function to close it: doing so could result in a "double close"
# and an "invalid file descriptor" exception.
PATH_TYPES = six.string_types
if HAS_PATHLIB:
PATH_TYPES += (pathlib.Path,)
close_fds = []
delete_fds = []
if remote_timeout is None:
# use configfile default
remote_timeout = conf.remote_timeout
# Get a file object to the content
if isinstance(name_or_obj, PATH_TYPES):
# name_or_obj could be a Path object if pathlib is available
if HAS_PATHLIB:
name_or_obj = str(name_or_obj)
is_url = _is_url(name_or_obj)
if is_url:
name_or_obj = download_file(
name_or_obj, cache=cache, show_progress=show_progress,
timeout=remote_timeout)
if six.PY2:
fileobj = open(name_or_obj, 'rb')
else:
fileobj = io.FileIO(name_or_obj, 'r')
if is_url and not cache:
delete_fds.append(fileobj)
close_fds.append(fileobj)
else:
fileobj = name_or_obj
# Check if the file object supports random access, and if not,
# then wrap it in a BytesIO buffer. It would be nicer to use a
# BufferedReader to avoid reading loading the whole file first,
# but that is not compatible with streams or urllib2.urlopen
# objects on Python 2.x.
if not hasattr(fileobj, 'seek'):
fileobj = io.BytesIO(fileobj.read())
# Now read enough bytes to look at signature
signature = fileobj.read(4)
fileobj.seek(0)
if signature[:3] == b'\x1f\x8b\x08': # gzip
import struct
try:
import gzip
fileobj_new = gzip.GzipFile(fileobj=fileobj, mode='rb')
fileobj_new.read(1) # need to check that the file is really gzip
except (IOError, EOFError): # invalid gzip file
fileobj.seek(0)
fileobj_new.close()
except struct.error: # invalid gzip file on Python 3
fileobj.seek(0)
fileobj_new.close()
else:
fileobj_new.seek(0)
fileobj = fileobj_new
elif signature[:3] == b'BZh': # bzip2
try:
import bz2
except ImportError:
for fd in close_fds:
fd.close()
raise ValueError(
".bz2 format files are not supported since the Python "
"interpreter does not include the bz2 module")
try:
# bz2.BZ2File does not support file objects, only filenames, so we
# need to write the data to a temporary file
with NamedTemporaryFile("wb", delete=False) as tmp:
tmp.write(fileobj.read())
tmp.close()
fileobj_new = bz2.BZ2File(tmp.name, mode='rb')
fileobj_new.read(1) # need to check that the file is really bzip2
except IOError: # invalid bzip2 file
fileobj.seek(0)
fileobj_new.close()
# raise
else:
fileobj_new.seek(0)
close_fds.append(fileobj_new)
fileobj = fileobj_new
elif signature[:3] == b'\xfd7z': # xz
try:
# for Python < 3.3 try backports.lzma; pyliblzma installs as lzma,
# but does not support TextIOWrapper
if sys.version_info >= (3,3,0):
import lzma
fileobj_new = lzma.LZMAFile(fileobj, mode='rb')
else:
from backports import lzma
from backports.lzma import LZMAFile
# when called with file object, returns a non-seekable instance
# need a filename here, too, so have to write the data to a
# temporary file
with NamedTemporaryFile("wb", delete=False) as tmp:
tmp.write(fileobj.read())
tmp.close()
fileobj_new = LZMAFile(tmp.name, mode='rb')
fileobj_new.read(1) # need to check that the file is really xz
except ImportError:
for fd in close_fds:
fd.close()
raise ValueError(
".xz format files are not supported since the Python "
"interpreter does not include the lzma module. "
"On Python versions < 3.3 consider installing backports.lzma")
except (IOError, EOFError) as e: # invalid xz file
fileobj.seek(0)
fileobj_new.close()
# should we propagate this to the caller to signal bad content?
# raise ValueError(e)
else:
fileobj_new.seek(0)
fileobj = fileobj_new
# By this point, we have a file, io.FileIO, gzip.GzipFile, bz2.BZ2File
# or lzma.LZMAFile instance opened in binary mode (that is, read
# returns bytes). Now we need to, if requested, wrap it in a
# io.TextIOWrapper so read will return unicode based on the
# encoding parameter.
if six.PY2:
needs_textio_wrapper = encoding != 'binary' and encoding is not None
else:
needs_textio_wrapper = encoding != 'binary'
if needs_textio_wrapper:
# A bz2.BZ2File can not be wrapped by a TextIOWrapper,
# so we decompress it to a temporary file and then
# return a handle to that.
try:
import bz2
except ImportError:
pass
else:
if isinstance(fileobj, bz2.BZ2File):
tmp = NamedTemporaryFile("wb", delete=False)
data = fileobj.read()
tmp.write(data)
tmp.close()
delete_fds.append(tmp)
if six.PY2:
fileobj = open(tmp.name, 'rb')
else:
fileobj = io.FileIO(tmp.name, 'r')
close_fds.append(fileobj)
# On Python 2.x, we need to first wrap the regular `file`
# instance in a `io.FileIO` object before it can be
# wrapped in a `TextIOWrapper`. We don't just create an
# `io.FileIO` object in the first place, because we can't
# get a raw file descriptor out of it on Python 2.x, which
# is required for the XML iterparser.
if six.PY2 and isinstance(fileobj, file):
fileobj = io.FileIO(fileobj.fileno())
fileobj = io.BufferedReader(fileobj)
fileobj = io.TextIOWrapper(fileobj, encoding=encoding)
# Ensure that file is at the start - io.FileIO will for
# example not always be at the start:
# >>> import io
# >>> f = open('test.fits', 'rb')
# >>> f.read(4)
# 'SIMP'
# >>> f.seek(0)
# >>> fileobj = io.FileIO(f.fileno())
# >>> fileobj.tell()
# 4096L
fileobj.seek(0)
try:
yield fileobj
finally:
for fd in close_fds:
fd.close()
for fd in delete_fds:
os.remove(fd.name)
def get_file_contents(*args, **kwargs):
"""
Retrieves the contents of a filename or file-like object.
See the `get_readable_fileobj` docstring for details on parameters.
Returns
-------
content
The content of the file (as requested by ``encoding``).
"""
with get_readable_fileobj(*args, **kwargs) as f:
return f.read()
def get_pkg_data_fileobj(data_name, package=None, encoding=None, cache=True):
"""
Retrieves a data file from the standard locations for the package and
provides the file as a file-like object that reads bytes.
Parameters
----------
data_name : str
Name/location of the desired data file. One of the following:
* The name of a data file included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data/file.dat'`` to get the
file in ``astropy/pkgname/data/file.dat``. Double-dots
can be used to go up a level. In the same example, use
``'../data/file.dat'`` to get ``astropy/data/file.dat``.
* If a matching local file does not exist, the Astropy
data server will be queried for the file.
* A hash like that produced by `compute_hash` can be
requested, prefixed by 'hash/'
e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash
will first be searched for locally, and if not found,
the Astropy data server will be queried.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that on Python 2.x returns `bytes` objects and
on Python 3.x returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
cache : bool
If True, the file will be downloaded and saved locally or the
already-cached local copy will be accessed. If False, the
file-like object will directly access the resource (e.g. if a
remote URL is accessed, an object like that from
`urllib2.urlopen` on Python 2 or `urllib.request.urlopen` on
Python 3 is returned).
Returns
-------
fileobj : file-like
An object with the contents of the data file available via
``read`` function. Can be used as part of a ``with`` statement,
automatically closing itself after the ``with`` block.
Raises
------
urllib2.URLError, urllib.error.URLError
If a remote file cannot be found.
IOError
If problems occur writing or reading a local file.
Examples
--------
This will retrieve a data file and its contents for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_fileobj
>>> with get_pkg_data_fileobj('data/3d_cd.hdr',
... package='astropy.wcs.tests') as fobj:
... fcontents = fobj.read()
...
This next example would download a data file from the astropy data server
because the ``allsky/allsky_rosat.fits`` file is not present in the
source distribution. It will also save the file locally so the
next time it is accessed it won't need to be downloaded.::
>>> from astropy.utils.data import get_pkg_data_fileobj
>>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
... encoding='binary') as fobj: # doctest: +REMOTE_DATA
... fcontents = fobj.read()
...
Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]
This does the same thing but does *not* cache it locally::
>>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
... encoding='binary', cache=False) as fobj: # doctest: +REMOTE_DATA
... fcontents = fobj.read()
...
Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]
See Also
--------
get_pkg_data_contents : returns the contents of a file or url as a bytes object
get_pkg_data_filename : returns a local name for a file containing the data
"""
datafn = _find_pkg_data_path(data_name, package=package)
if os.path.isdir(datafn):
raise IOError("Tried to access a data file that's actually "
"a package data directory")
elif os.path.isfile(datafn): # local file
return get_readable_fileobj(datafn, encoding=encoding)
else: # remote file
return get_readable_fileobj(conf.dataurl + datafn, encoding=encoding,
cache=cache)
def get_pkg_data_filename(data_name, package=None, show_progress=True,
remote_timeout=None):
"""
Retrieves a data file from the standard locations for the package and
provides a local filename for the data.
This function is similar to `get_pkg_data_fileobj` but returns the
file *name* instead of a readable file-like object. This means
that this function must always cache remote files locally, unlike
`get_pkg_data_fileobj`.
Parameters
----------
data_name : str
Name/location of the desired data file. One of the following:
* The name of a data file included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data/file.dat'`` to get the
file in ``astropy/pkgname/data/file.dat``. Double-dots
can be used to go up a level. In the same example, use
``'../data/file.dat'`` to get ``astropy/data/file.dat``.
* If a matching local file does not exist, the Astropy
data server will be queried for the file.
* A hash like that produced by `compute_hash` can be
requested, prefixed by 'hash/'
e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash
will first be searched for locally, and if not found,
the Astropy data server will be queried.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
show_progress : bool, optional
Whether to display a progress bar if the file is downloaded
from a remote server. Default is `True`.
remote_timeout : float
Timeout for the requests in seconds (default is the
configurable `astropy.utils.data.Conf.remote_timeout`, which
is 3s by default)
Raises
------
urllib2.URLError, urllib.error.URLError
If a remote file cannot be found.
IOError
If problems occur writing or reading a local file.
Returns
-------
filename : str
A file path on the local file system corresponding to the data
requested in ``data_name``.
Examples
--------
This will retrieve the contents of the data file for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_filename
>>> fn = get_pkg_data_filename('data/3d_cd.hdr',
... package='astropy.wcs.tests')
>>> with open(fn) as f:
... fcontents = f.read()
...
This retrieves a data file by hash either locally or from the astropy data
server::
>>> from astropy.utils.data import get_pkg_data_filename
>>> fn = get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28') # doctest: +SKIP
>>> with open(fn) as f:
... fcontents = f.read()
...
See Also
--------
get_pkg_data_contents : returns the contents of a file or url as a bytes object
get_pkg_data_fileobj : returns a file-like object with the data
"""
data_name = os.path.normpath(data_name)
if remote_timeout is None:
# use configfile default
remote_timeout = conf.remote_timeout
if data_name.startswith('hash/'):
# first try looking for a local version if a hash is specified
hashfn = _find_hash_fn(data_name[5:])
if hashfn is None:
return download_file(
conf.dataurl + data_name, cache=True,
show_progress=show_progress,
timeout=remote_timeout)
else:
return hashfn
else:
datafn = _find_pkg_data_path(data_name, package=package)
if os.path.isdir(datafn):
raise IOError("Tried to access a data file that's actually "
"a package data directory")
elif os.path.isfile(datafn): # local file
return datafn
else: # remote file
return download_file(
conf.dataurl + data_name, cache=True,
show_progress=show_progress,
timeout=remote_timeout)
def get_pkg_data_contents(data_name, package=None, encoding=None, cache=True):
"""
Retrieves a data file from the standard locations and returns its
contents as a bytes object.
Parameters
----------
data_name : str
Name/location of the desired data file. One of the following:
* The name of a data file included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data/file.dat'`` to get the
file in ``astropy/pkgname/data/file.dat``. Double-dots
can be used to go up a level. In the same example, use
``'../data/file.dat'`` to get ``astropy/data/file.dat``.
* If a matching local file does not exist, the Astropy
data server will be queried for the file.
* A hash like that produced by `compute_hash` can be
requested, prefixed by 'hash/'
e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash
will first be searched for locally, and if not found,
the Astropy data server will be queried.
* A URL to some other file.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that on Python 2.x returns `bytes` objects and
on Python 3.x returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
cache : bool
If True, the file will be downloaded and saved locally or the
already-cached local copy will be accessed. If False, the
file-like object will directly access the resource (e.g. if a
remote URL is accessed, an object like that from
`urllib2.urlopen` on Python 2 or `urllib.request.urlopen` on
Python 3 is returned).
Returns
-------
contents : bytes
The complete contents of the file as a bytes object.
Raises
------
urllib2.URLError, urllib.error.URLError
If a remote file cannot be found.
IOError
If problems occur writing or reading a local file.
See Also
--------
get_pkg_data_fileobj : returns a file-like object with the data
get_pkg_data_filename : returns a local name for a file containing the data
"""
with get_pkg_data_fileobj(data_name, package=package, encoding=encoding,
cache=cache) as fd:
contents = fd.read()
return contents
def get_pkg_data_filenames(datadir, package=None, pattern='*'):
"""
Returns the path of all of the data files in a given directory
that match a given glob pattern.
Parameters
----------
datadir : str
Name/location of the desired data files. One of the following:
* The name of a directory included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data'`` to get the
files in ``astropy/pkgname/data``.
* Remote URLs are not currently supported.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
pattern : str, optional
A UNIX-style filename glob pattern to match files. See the
`glob` module in the standard library for more information.
By default, matches all files.
Returns
-------
filenames : iterator of str
Paths on the local filesystem in *datadir* matching *pattern*.
Examples
--------
This will retrieve the contents of the data file for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_filenames
>>> for fn in get_pkg_data_filenames('maps', 'astropy.wcs.tests',
... '*.hdr'):
... with open(fn) as f:
... fcontents = f.read()
...
"""
path = _find_pkg_data_path(datadir, package=package)
if os.path.isfile(path):
raise IOError(
"Tried to access a data directory that's actually "
"a package data file")
elif os.path.isdir(path):
for filename in os.listdir(path):
if fnmatch.fnmatch(filename, pattern):
yield os.path.join(path, filename)
else:
raise IOError("Path not found")
def get_pkg_data_fileobjs(datadir, package=None, pattern='*', encoding=None):
"""
Returns readable file objects for all of the data files in a given
directory that match a given glob pattern.
Parameters
----------
datadir : str
Name/location of the desired data files. One of the following:
* The name of a directory included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data'`` to get the
files in ``astropy/pkgname/data``
* Remote URLs are not currently supported
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
pattern : str, optional
A UNIX-style filename glob pattern to match files. See the
`glob` module in the standard library for more information.
By default, matches all files.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that on Python 2.x returns `bytes` objects and
on Python 3.x returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
Returns
-------
fileobjs : iterator of file objects
File objects for each of the files on the local filesystem in
*datadir* matching *pattern*.
Examples
--------
This will retrieve the contents of the data file for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_filenames
>>> for fd in get_pkg_data_fileobjs('maps', 'astropy.wcs.tests',
... '*.hdr'):
... fcontents = fd.read()
...
"""
for fn in get_pkg_data_filenames(datadir, package=package,
pattern=pattern):
with get_readable_fileobj(fn, encoding=encoding) as fd:
yield fd
def compute_hash(localfn):
""" Computes the MD5 hash for a file.
The hash for a data file is used for looking up data files in a unique
fashion. This is of particular use for tests; a test may require a
particular version of a particular file, in which case it can be accessed
via hash to get the appropriate version.
Typically, if you wish to write a test that requires a particular data
file, you will want to submit that file to the astropy data servers, and
use
e.g. ``get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')``,
but with the hash for your file in place of the hash in the example.
Parameters
----------
localfn : str
The path to the file for which the hash should be generated.
Returns
-------
md5hash : str
The hex digest of the MD5 hash for the contents of the ``localfn``
file.
"""
with open(localfn, 'rb') as f:
h = hashlib.md5()
block = f.read(conf.compute_hash_block_size)
while block:
h.update(block)
block = f.read(conf.compute_hash_block_size)
return h.hexdigest()
def _find_pkg_data_path(data_name, package=None):
"""
Look for data in the source-included data directories and return the
path.
"""
if package is None:
module = find_current_module(1, True)
if module is None:
# not called from inside an astropy package. So just pass name
# through
return data_name
if not hasattr(module, '__package__') or not module.__package__:
# The __package__ attribute may be missing or set to None; see
# PEP-366, also astropy issue #1256
if '.' in module.__name__:
package = module.__name__.rpartition('.')[0]
else:
package = module.__name__
else:
package = module.__package__
else:
module = resolve_name(package)
rootpkgname = package.partition('.')[0]
rootpkg = resolve_name(rootpkgname)
module_path = os.path.dirname(module.__file__)
path = os.path.join(module_path, data_name)
root_dir = os.path.dirname(rootpkg.__file__)
assert _is_inside(path, root_dir), \
("attempted to get a local data file outside "
"of the " + rootpkgname + " tree")
return path
def _find_hash_fn(hash):
"""
Looks for a local file by hash - returns file name if found and a valid
file, otherwise returns None.
"""
try:
dldir, urlmapfn = _get_download_cache_locs()
except (IOError, OSError) as e:
msg = 'Could not access cache directory to search for data file: '
warn(CacheMissingWarning(msg + str(e)))
return None
hashfn = os.path.join(dldir, hash)
if os.path.isfile(hashfn):
return hashfn
else:
return None
def get_free_space_in_dir(path):
"""
Given a path to a directory, returns the amount of free space (in
bytes) on that filesystem.
Parameters
----------
path : str
The path to a directory
Returns
-------
bytes : int
The amount of free space on the partition that the directory
is on.
"""
if sys.platform.startswith('win'):
import ctypes
free_bytes = ctypes.c_ulonglong(0)
retval = ctypes.windll.kernel32.GetDiskFreeSpaceExW(
ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes))
if retval == 0:
raise IOError('Checking free space on {!r} failed '
'unexpectedly.'.format(path))
return free_bytes.value
else:
stat = os.statvfs(path)
return stat.f_bavail * stat.f_frsize
def check_free_space_in_dir(path, size):
"""
Determines if a given directory has enough space to hold a file of
a given size. Raises an IOError if the file would be too large.
Parameters
----------
path : str
The path to a directory
size : int
A proposed filesize (in bytes)
Raises
-------
IOError : There is not enough room on the filesystem
"""
from ..utils.console import human_file_size
space = get_free_space_in_dir(path)
if space < size:
raise IOError(
"Not enough free space in '{0}' "
"to download a {1} file".format(
path, human_file_size(size)))
def download_file(remote_url, cache=False, show_progress=True, timeout=None):
"""
Accepts a URL, downloads and optionally caches the result
returning the filename, with a name determined by the file's MD5
hash. If ``cache=True`` and the file is present in the cache, just
returns the filename.
Parameters
----------
remote_url : str
The URL of the file to download
cache : bool, optional
Whether to use the cache
show_progress : bool, optional
Whether to display a progress bar during the download (default
is `True`)
timeout : float, optional
The timeout, in seconds. Otherwise, use
`astropy.utils.data.Conf.remote_timeout`.
Returns
-------
local_path : str
Returns the local path that the file was download to.
Raises
------
urllib2.URLError, urllib.error.URLError
Whenever there's a problem getting the remote file.
"""
from ..utils.console import ProgressBarOrSpinner
if timeout is None:
timeout = conf.remote_timeout
missing_cache = False
if timeout is None:
# use configfile default
timeout = conf.remote_timeout()
if cache:
try:
dldir, urlmapfn = _get_download_cache_locs()
except (IOError, OSError) as e:
msg = 'Remote data cache could not be accessed due to '
estr = '' if len(e.args) < 1 else (': ' + str(e))
warn(CacheMissingWarning(msg + e.__class__.__name__ + estr))
cache = False
missing_cache = True # indicates that the cache is missing to raise a warning later
if six.PY2 and isinstance(remote_url, six.text_type):
# shelve DBs don't accept unicode strings in Python 2
url_key = remote_url.encode('utf-8')
else:
url_key = remote_url
try:
if cache:
# We don't need to acquire the lock here, since we are only reading
with _open_shelve(urlmapfn, True) as url2hash:
if url_key in url2hash:
return url2hash[url_key]
with contextlib.closing(urllib.request.urlopen(
remote_url, timeout=timeout)) as remote:
#keep a hash to rename the local file to the hashed name
hash = hashlib.md5()
info = remote.info()
if 'Content-Length' in info:
try:
size = int(info['Content-Length'])
except ValueError:
size = None
else:
size = None
if size is not None:
check_free_space_in_dir(gettempdir(), size)
if cache:
check_free_space_in_dir(dldir, size)
if show_progress:
progress_stream = sys.stdout
else:
progress_stream = io.StringIO()
dlmsg = "Downloading {0}".format(remote_url)
with ProgressBarOrSpinner(size, dlmsg, file=progress_stream) as p:
with NamedTemporaryFile(delete=False) as f:
try:
bytes_read = 0
block = remote.read(conf.download_block_size)
while block:
f.write(block)
hash.update(block)
bytes_read += len(block)
p.update(bytes_read)
block = remote.read(conf.download_block_size)
except BaseException:
if os.path.exists(f.name):
os.remove(f.name)
raise
if cache:
_acquire_download_cache_lock()
try:
with _open_shelve(urlmapfn, True) as url2hash:
# We check now to see if another process has
# inadvertently written the file underneath us
# already
if url_key in url2hash:
return url2hash[url_key]
local_path = os.path.join(dldir, hash.hexdigest())
shutil.move(f.name, local_path)
url2hash[url_key] = local_path
finally:
_release_download_cache_lock()
else:
local_path = f.name
if missing_cache:
msg = ('File downloaded to temporary location due to problem '
'with cache directory and will not be cached.')
warn(CacheMissingWarning(msg, local_path))
if conf.delete_temporary_downloads_at_exit:
global _tempfilestodel
_tempfilestodel.append(local_path)
except urllib.error.URLError as e:
if hasattr(e, 'reason') and hasattr(e.reason, 'errno') and e.reason.errno == 8:
e.reason.strerror = e.reason.strerror + '. requested URL: ' + remote_url
e.reason.args = (e.reason.errno, e.reason.strerror)
raise e
except socket.timeout as e:
# this isn't supposed to happen, but occasionally a socket.timeout gets
# through. It's supposed to be caught in `urrlib2` and raised in this
# way, but for some reason in mysterious circumstances it doesn't. So
# we'll just re-raise it here instead
raise urllib.error.URLError(e)
return local_path
def is_url_in_cache(url_key):
"""
Check if a download from ``url_key`` is in the cache.
Parameters
----------
url_key : string
The URL retrieved
Returns
-------
in_cache : bool
`True` if a download from ``url_key`` is in the cache
"""
# The code below is modified from astropy.utils.data.download_file()
try:
dldir, urlmapfn = _get_download_cache_locs()
except (IOError, OSError) as e:
msg = 'Remote data cache could not be accessed due to '
estr = '' if len(e.args) < 1 else (': ' + str(e))
warn(CacheMissingWarning(msg + e.__class__.__name__ + estr))
return False
if six.PY2 and isinstance(url_key, six.text_type):
# shelve DBs don't accept unicode strings in Python 2
url_key = url_key.encode('utf-8')
with _open_shelve(urlmapfn, True) as url2hash:
if url_key in url2hash:
return True
return False
def _do_download_files_in_parallel(args):
return download_file(*args, show_progress=False)
def download_files_in_parallel(urls, cache=False, show_progress=True,
timeout=None):
"""
Downloads multiple files in parallel from the given URLs. Blocks until
all files have downloaded. The result is a list of local file paths
corresponding to the given urls.
Parameters
----------
urls : list of str
The URLs to retrieve.
cache : bool, optional
Whether to use the cache
show_progress : bool, optional
Whether to display a progress bar during the download (default
is `True`)
timeout : float, optional
Timeout for the requests in seconds (default is the
configurable `astropy.utils.data.Conf.remote_timeout`).
Returns
-------
paths : list of str
The local file paths corresponding to the downloaded URLs.
"""
from .console import ProgressBar
if timeout is None:
timeout = conf.remote_timeout
if show_progress:
progress = sys.stdout
else:
progress = io.BytesIO()
if timeout is None:
# use configfile default
timeout = REMOTE_TIMEOUT()
# Combine duplicate URLs
combined_urls = list(set(urls))
combined_paths = ProgressBar.map(
_do_download_files_in_parallel,
[(x, cache) for x in combined_urls],
file=progress,
multiprocess=True)
paths = []
for url in urls:
paths.append(combined_paths[combined_urls.index(url)])
return paths
# This is used by download_file and _deltemps to determine the files to delete
# when the interpreter exits
_tempfilestodel = []
@atexit.register
def _deltemps():
global _tempfilestodel
if _tempfilestodel is not None:
while len(_tempfilestodel) > 0:
fn = _tempfilestodel.pop()
if os.path.isfile(fn):
os.remove(fn)
def clear_download_cache(hashorurl=None):
""" Clears the data file cache by deleting the local file(s).
Parameters
----------
hashorurl : str or None
If None, the whole cache is cleared. Otherwise, either specifies a
hash for the cached file that is supposed to be deleted, or a URL that
should be removed from the cache if present.
"""
try:
dldir, urlmapfn = _get_download_cache_locs()
except (IOError, OSError) as e:
msg = 'Not clearing data cache - cache inacessable due to '
estr = '' if len(e.args) < 1 else (': ' + str(e))
warn(CacheMissingWarning(msg + e.__class__.__name__ + estr))
return
_acquire_download_cache_lock()
try:
if hashorurl is None:
# dldir includes both the download files and the urlmapfn. This structure
# is required since we cannot know a priori the actual file name corresponding
# to the shelve map named urlmapfn.
if os.path.exists(dldir):
shutil.rmtree(dldir)
else:
with _open_shelve(urlmapfn, True) as url2hash:
filepath = os.path.join(dldir, hashorurl)
assert _is_inside(filepath, dldir), \
("attempted to use clear_download_cache on a path "
"outside the data cache directory")
# shelve DBs don't accept unicode strings as keys in Python 2
if six.PY2 and isinstance(hashorurl, six.text_type):
hash_key = hashorurl.encode('utf-8')
else:
hash_key = hashorurl
if os.path.exists(filepath):
for k, v in six.iteritems(url2hash):
if v == filepath:
del url2hash[k]
os.unlink(filepath)
elif hash_key in url2hash:
filepath = url2hash[hash_key]
del url2hash[hash_key]
if os.path.exists(filepath):
# Make sure the filepath still actually exists (perhaps user removed it)
os.unlink(filepath)
# Otherwise could not find file or url, but no worries.
# Clearing download cache just makes sure that the file or url
# is no longer in the cache regardless of starting condition.
finally:
# the lock will be gone if rmtree was used above, but release otherwise
if os.path.exists(os.path.join(dldir, 'lock')):
_release_download_cache_lock()
def _get_download_cache_locs():
""" Finds the path to the data cache directory and makes them if
they don't exist.
Returns
-------
datadir : str
The path to the data cache directory.
shelveloc : str
The path to the shelve object that stores the cache info.
"""
from ..config.paths import get_cache_dir
# datadir includes both the download files and the shelveloc. This structure
# is required since we cannot know a priori the actual file name corresponding
# to the shelve map named shelveloc. (The backend can vary and is allowed to
# do whatever it wants with the filename. Filename munging can and does happen
# in practice).
py_version = 'py' + str(sys.version_info.major)
datadir = os.path.join(get_cache_dir(), 'download', py_version)
shelveloc = os.path.join(datadir, 'urlmap')
if not os.path.exists(datadir):
try:
os.makedirs(datadir)
except OSError as e:
if not os.path.exists(datadir):
raise
elif not os.path.isdir(datadir):
msg = 'Data cache directory {0} is not a directory'
raise IOError(msg.format(datadir))
if os.path.isdir(shelveloc):
msg = 'Data cache shelve object location {0} is a directory'
raise IOError(msg.format(shelveloc))
return datadir, shelveloc
def _open_shelve(shelffn, withclosing=False):
"""
Opens a shelf file. If `withclosing` is True, it will be opened with closing,
allowing use like:
with _open_shelve('somefile',True) as s:
...
"""
import shelve
shelf = shelve.open(shelffn, protocol=2)
if withclosing:
return contextlib.closing(shelf)
else:
return shelf
#the cache directory must be locked before any writes are performed. Same for
#the hash shelve, so this should be used for both.
def _acquire_download_cache_lock():
"""
Uses the lock directory method. This is good because `mkdir` is
atomic at the system call level, so it's thread-safe.
"""
lockdir = os.path.join(_get_download_cache_locs()[0], 'lock')
for i in range(conf.download_cache_lock_attempts):
try:
os.mkdir(lockdir)
#write the pid of this process for informational purposes
with open(os.path.join(lockdir, 'pid'), 'w') as f:
f.write(str(os.getpid()))
except OSError:
time.sleep(1)
else:
return
msg = ("Unable to acquire lock for cache directory ({0} exists). "
"You may need to delete the lock if the python interpreter wasn't "
"shut down properly.")
raise RuntimeError(msg.format(lockdir))
def _release_download_cache_lock():
lockdir = os.path.join(_get_download_cache_locs()[0], 'lock')
if os.path.isdir(lockdir):
#if the pid file is present, be sure to remove it
pidfn = os.path.join(lockdir, 'pid')
if os.path.exists(pidfn):
os.remove(pidfn)
os.rmdir(lockdir)
else:
msg = 'Error releasing lock. "{0}" either does not exist or is not ' +\
'a directory.'
raise RuntimeError(msg.format(lockdir))
|