ó 2ÄÈ[c@`sædZddlmZmZmZddlZddlZddlZddlZddl Z e Z d„Z d„Z d„Zdefd„ƒYZeƒZd ejeed „Z d efd „ƒYZd efd„ƒYZdS(sßA file interface for handling local and remote data files. The goal of datasource is to abstract some of the file system operations when dealing with data files so the researcher doesn't have to know all the low-level details. Through datasource, a researcher can obtain and use a file with one function call, regardless of location of the file. DataSource is meant to augment standard python libraries, not replace them. It should work seamlessly with standard file IO operations and the os module. DataSource files can originate locally or remotely: - local files : '/home/guido/src/local/data.txt' - URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt' DataSource files can also be compressed or uncompressed. Currently only gzip, bz2 and xz are supported. Example:: >>> # Create a DataSource, use os.curdir (default) for local storage. >>> ds = datasource.DataSource() >>> >>> # Open a remote file. >>> # DataSource downloads the file, stores it locally in: >>> # './www.google.com/index.html' >>> # opens the file and returns a file object. >>> fp = ds.open('http://www.google.com/index.html') >>> >>> # Use the file as you normally would >>> fp.read() >>> fp.close() i(tdivisiontabsolute_importtprint_functionNcC`skd|kr1d|krgtd|fƒ‚qgn6|dk rLtdƒ‚n|dk rgtdƒ‚ndS(sàCheck mode and that encoding and newline are compatible. Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files. tttbsInvalid mode: %rs0Argument 'encoding' not supported in binary modes/Argument 'newline' not supported in binary modeN(t ValueErrortNone(tmodetencodingtnewline((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt _check_mode.s    cC`scddl}t|||ƒd|krStjdtddƒ|jddƒ}n|j||ƒS(sRWrapper to open bz2 in text mode. Parameters ---------- fn : str File name mode : {'r', 'w'} File mode. Note that bz2 Text files are not supported. encoding : str Ignored, text bz2 files not supported in Python2. newline : str Ignored, text bz2 files not supported in Python2. iNRs5Assuming latin1 encoding for bz2 text file in Python2t stacklevelit(tbz2R twarningstwarntRuntimeWarningtreplacetBZ2File(tfnRRR R ((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt_python2_bz2openEs    cC`sÚddl}d|jfd„ƒY}t|||ƒ|jddƒ}t|ttfƒrn|||ƒ}nBt|dƒsŒt|dƒr¤|d|d |ƒ}n t d ƒ‚d|krÒt j ||d |ƒS|SdS( s¬ Wrapper to open gzip in text mode. Parameters ---------- fn : str, bytes, file File path or opened file. mode : str File mode. The actual files are opened as binary, but will decoded using the specified `encoding` and `newline`. encoding : str Encoding to be used when reading/writing as text. newline : str Newline to be used when reading/writing as text. iNtGzipWrapcB`seZd„ZRS(cS`s |j|ƒS(N(tread(tselftn((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pytread1qs(t__name__t __module__R(((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRpsRR Rtwritetfileobjs1filename must be a str or bytes object, or a fileR ( tgziptGzipFileR Rt isinstancetstrtbytesthasattrRt TypeErrortiot TextIOWrapper(RRRR RRtgz_modet binary_file((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt_python2_gzipopen^s   t _FileOpenerscB`s2eZdZd„Zd„Zd„Zd„ZRS(sö Container for different methods to open (un-)compressed files. `_FileOpeners` contains a dictionary that holds one method for each supported file format. Attribute lookup is implemented in such a way that an instance of `_FileOpeners` itself can be indexed with the keys of that dictionary. Currently uncompressed files as well as files compressed with ``gzip``, ``bz2`` or ``xz`` compression are supported. Notes ----- `_file_openers`, an instance of `_FileOpeners`, is made available for use in the `_datasource` module. Examples -------- >>> np.lib._datasource._file_openers.keys() [None, '.bz2', '.gz', '.xz', '.lzma'] >>> np.lib._datasource._file_openers['.gz'] is gzip.open True cC`s t|_itjd6|_dS(N(tFalset_loadedR%topenRt _file_openers(R((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt__init__¢s cC`s|jr dSyCddl}tjddkrB|j|jd>> repos = DataSource() >>> repos.exists('www.google.com/index.html') False >>> repos.exists('http://www.google.com/index.html') True Temporary directories are deleted when the DataSource is deleted. Examples -------- :: >>> ds = DataSource('/home/guido') >>> urlname = 'http://www.google.com/index.html' >>> gfile = ds.open('http://www.google.com/index.html') # remote file >>> ds.abspath(urlname) '/home/guido/www.google.com/site/index.html' >>> ds = DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') >>> ds.abspath('/home/guido/foobar.txt') '/tmp/tmpy4pgsP/home/guido/foobar.txt' cC`sO|r'tjj|ƒ|_t|_n$ddl}|jƒ|_t|_dS(s2Create a DataSource with a local path at destpath.iN( tosR>tabspatht _destpathR+t _istmpdestttempfiletmkdtempR5(RR?RE((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyR/:s   cC`s |jrtj|jƒndS(N(RDtshutiltrmtreeRC(R((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt__del__Ds cC`s(tjj|ƒ\}}|tjƒkS(sNTest if the filename is a zip file by looking at the file extension. (RAR>tsplitextR.R8(Rtfilenametfnametext((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt_iszipIscC`s+d}x|D]}||kr tSq WtS(s4Test if the given mode will open a file for writing.twt+(RORP(R5R+(RRt _writemodestc((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt _iswritemodePs   cC`s-|j|ƒrtjj|ƒS|dfSdS(sxSplit zip extension from filename and return filename. *Returns*: base, zip_ext : {tuple} N(RNRAR>RJR(RRK((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt _splitzipextZscC`sP|g}|j|ƒsLx1tjƒD] }|r%|j||ƒq%q%Wn|S(s9Return a tuple containing compressed filename variations.(RNR.R8tappend(RRKtnamestzipext((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt_possible_namesgs  c C`sdtjddkr&ddlm}nddlm}||ƒ\}}}}}}t|o`|ƒS(s=Test if path is a net location. Tests the scheme and netloc.ii(turlparse(R0R1t urllib.parseRYtbool( RR>RYtschemetnetloctupathtuparamstuquerytufrag((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt_isurlps cC`s4tjddkr6ddlm}ddlm}n ddlm}ddlm}|j|ƒ}tj j tj j |ƒƒsŸtj tj j |ƒƒn|j |ƒr yK||ƒ}t|dƒ}ztj||ƒWd|jƒ|jƒXWq0|k r|d|ƒ‚q0Xntj||ƒ|S(shCache the file specified by path. Creates a copy of the file in the datasource cache. ii(turlopen(tURLErrortwbNsURL not found: %s(R0R1turllib.requestRct urllib.errorRdturllib2RBRAR>texiststdirnametmakedirsRbt_openRGt copyfileobjtclosetcopyfile(RR>RcRdR^t openedurltf((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt_cache‚s(   cC`s±|j|ƒs=|j|ƒ}||j|j|ƒƒ7}n+|j|j|ƒƒ}||j|ƒ}xB|D]:}|j|ƒro|j|ƒr¥|j|ƒ}n|SqoWdS(sySearches for ``path`` and returns full path if found. If path is an URL, _findfile will cache a local copy and return the path to the cached file. If path is a local file, _findfile will return a path to that local file. The search will include possible compressed versions of the file and return the first occurrence found. N(RbRXRBRiRrR(RR>tfilelisttname((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt _findfile§s  c C`s¿tjddkr&ddlm}nddlm}|j|jdƒ}t|ƒdkrj|d}n||ƒ\}}}}}} |j|ƒ}|j|ƒ}tj j |j||ƒS(sF Return absolute path of file in the DataSource directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str Can be a local file or a remote URL. Returns ------- out : str Complete path, including the `DataSource` destination directory. Notes ----- The functionality is based on `os.path.abspath`. ii(RYii( R0R1RZRYtsplitRCtlent_sanitize_relative_pathRAR>tjoin( RR>RYt splitpathR\R]R^R_R`Ra((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRBÆs  cC`sƒd}tjj|ƒ}xd||kr~|}|jtjƒjdƒ}|jtjƒjdƒ}tjj|ƒ\}}qW|S(svReturn a sanitised relative path for which os.path.abspath(os.path.join(base, path)).startswith(base) t/s..N(RRAR>tnormpathtlstriptseptpardirt splitdrive(RR>tlasttdrive((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRxóscC`sÝtjddkr6ddlm}ddlm}n ddlm}ddlm}tjj |ƒrlt S|j |ƒ}tjj |ƒr‘t S|j |ƒrÙy!||ƒ}|j ƒ~t SWqÙ|k rÕtSXntS(s3 Test if path exists. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str Can be a local file or a remote URL. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. ii(Rc(Rd(R0R1RfRcRgRdRhRAR>RiR5RBRbRnR+(RR>RcRdR^tnetfile((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRis&    R<cC`sª|j|ƒr-|j|ƒr-tdƒ‚n|j|ƒ}|r–|j|ƒ\}}|dkrv|jddƒnt||d|d|d|ƒStd|ƒ‚d S( sD Open and return file-like object. If `path` is an URL, it will be downloaded, stored in the `DataSource` directory and opened from there. Parameters ---------- path : str Local file path or URL to open. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. sURLs are not writeableR RPR RRR s %s not found.N(RbRSRRuRTRR.tIOError(RR>RRR tfoundt_fnameRM((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyR-<s"  N(RRR;RAtcurdirR/RIRNRSRTRXRbRrRuRBRxRiRR-(((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyR= s/    %  -  ;t RepositorycB`seeZdZejd„Zd„Zd„Zd„Zd„Z d„Z dd d d„Z d „Z RS( s Repository(baseurl, destpath='.') A data repository where multiple DataSource's share a base URL/directory. `Repository` extends `DataSource` by prepending a base URL (or directory) to all the files it handles. Use `Repository` when you will be working with multiple files from one base URL. Initialize `Repository` with the base URL, then refer to each file by its filename only. Parameters ---------- baseurl : str Path to the local directory or remote location that contains the data files. destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Examples -------- To analyze all files in the repository, do something like this (note: this is not self-contained code):: >>> repos = np.lib._datasource.Repository('/home/user/data/dir/') >>> for filename in filelist: ... fp = repos.open(filename) ... fp.analyze() ... fp.close() Similarly you could use a URL for a repository:: >>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data') cC`s tj|d|ƒ||_dS(s>Create a Repository with a shared url or directory of baseurl.R?N(R=R/t_baseurl(RtbaseurlR?((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyR/•scC`stj|ƒdS(N(R=RI(R((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRIšscC`sL|j|jdƒ}t|ƒdkrBtjj|j|ƒ}n|}|S(s>Return complete path for path. Prepends baseurl if necessary.ii(RvR‰RwRAR>Ry(RR>Rztresult((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt _fullpaths cC`stj||j|ƒƒS(s8Extend DataSource method to prepend baseurl to ``path``.(R=RuRŒ(RR>((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRu¦scC`stj||j|ƒƒS(sk Return absolute path of file in the Repository directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : str Complete path, including the `DataSource` destination directory. (R=RBRŒ(RR>((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRBªscC`stj||j|ƒƒS(sÕ Test if path exists prepending Repository base URL to path. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. (R=RiRŒ(RR>((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRiÁs R<cC`s(tj||j|ƒ|d|d|ƒS(sÜ Open and return file-like object prepending Repository base URL. If `path` is an URL, it will be downloaded, stored in the DataSource directory and opened from there. Parameters ---------- path : str Local file path or URL to open. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. RR (R=R-RŒ(RR>RRR ((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyR-ãscC`s5|j|jƒr!tdƒ‚ntj|jƒSdS(s  List files in the source Repository. Returns ------- files : list of str List of file names (not containing a directory part). Notes ----- Does not currently work for remote repositories. s-Directory listing of URLs, not supported yet.N(RbR‰tNotImplementedErrorRAtlistdir(R((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRŽs N(RRR;RAR‡R/RIRŒRuRBRiRR-RŽ(((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyRˆms&    " (R;t __future__RRRRAR0RRGR%R-RlR RR)tobjectR*R.R‡RR=Rˆ(((s4/tmp/pip-build-fiC0ax/numpy/numpy/lib/_datasource.pyt#s         ,T )ÿe