Changeset 14437

Show
Ignore:
Timestamp:
05/10/08 17:12:40 (2 months ago)
Author:
rouault
Message:

Add gdaltest.download_file that enables to download test data files if GDAL_DOWNLOAD_TEST_DATA environment variable is defined and cache them for later faster use

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/autotest/pymod/gdaltest.py

    r14120 r14437  
    3131import string 
    3232import os 
     33import urllib2 
    3334try: 
    3435    from osgeo import gdal 
     
    5051 
    5152argv = gdal.GeneralCmdLineProcessor( sys.argv ) 
    52  
    5353 
    5454############################################################################### 
     
    832832 
    833833    return 1 
     834 
     835 
     836############################################################################### 
     837# Download file at url 'url' and put it as 'filename' in 'tmp/cache/' 
     838# 
     839# If 'filename' already exits in 'tmp/cache/', it is not downloaded 
     840# If GDAL_DOWNLOAD_TEST_DATA is not defined, the function fails 
     841# If GDAL_DOWNLOAD_TEST_DATA is defined, 'url' is downloaded  as 'filename' in 'tmp/cache/' 
     842 
     843def download_file(url, filename): 
     844    try: 
     845        os.stat( 'tmp/cache/' + filename ) 
     846        return True 
     847    except: 
     848        if os.environ.has_key('GDAL_DOWNLOAD_TEST_DATA'): 
     849            val = None 
     850            try: 
     851                handle = urllib2.urlopen(url) 
     852                print 'Downloading %s...' % (url) 
     853                val = handle.read() 
     854            except urllib2.HTTPError, e: 
     855                print 'HTTP service for %s is down (HTTP Error: %d)' % (url, e.code) 
     856                return False 
     857            except: 
     858                print 'HTTP service for %s is down.' %(url) 
     859                return False 
     860 
     861            try: 
     862                os.stat( 'tmp/cache' ) 
     863            except: 
     864                os.mkdir('tmp/cache') 
     865 
     866            try: 
     867                open( 'tmp/cache/' + filename, 'wb').write(val) 
     868                return True 
     869            except: 
     870                print 'Cannot write %s' % (filename) 
     871                return False 
     872        else: 
     873            return False