1+ """Utility routines to download CryoSat-2 files"""
2+
3+ import os
4+ import platform
5+ from ftplib import FTP
6+ import sys
7+ from typing import Union , List
8+
9+ from pathlib import Path
10+
11+
12+ def get_padded_count (count , max_count ):
13+ return str (count ).zfill (len (str (max_count )))
14+
15+
16+ def file_byte_handler (data ):
17+ global download_file_obj , read_byte_count , total_byte_count
18+ download_file_obj .write (data )
19+ read_byte_count = read_byte_count + len (data )
20+ progress_bar (read_byte_count , total_byte_count )
21+
22+
23+ def progress_bar (progress , total , prefix = "" , size = 60 , file = sys .stdout ):
24+ if total != 0 :
25+ x = int (size * progress / total )
26+ x_percent = int (100 * progress / total )
27+ file .write (f" { prefix } [{ '=' * x } { ' ' * (size - x )} ] { x_percent } % \r " )
28+ file .flush ()
29+
30+
31+ def download_files (user_email : str , esa_files : List [str ], dir : Union [str ,Path ]= "." ):
32+ """Downloads CryoSat-2 Files from ESA ftp
33+
34+ Arguments
35+ ---------
36+ user_email : email to use for anonymous ftp login
37+ esa_files : list of paths to cryosat-2 files
38+ dir : output directory path. Default is current working directory.
39+ If dir does not exist it is created.
40+
41+ Returns
42+ -------
43+ list of paths to downloaded files
44+ """
45+ global download_file_obj , read_byte_count , total_byte_count
46+
47+ if not isinstance (dir , Path ):
48+ dir = Path (dir )
49+
50+ if not dir .exists ():
51+ if not dir .exists ():
52+ print ("Download path dir does not exist. Creating dir" )
53+ dir .mkdir (parents = True , exist_ok = True )
54+
55+ print ("About to connect to ESA science server" )
56+ with FTP ("science-pds.cryosat.esa.int" ) as ftp :
57+ try :
58+ ftp .login ("anonymous" , user_email )
59+ print ("Downloading {} files" .format (len (esa_files )))
60+
61+ download_path_list = []
62+ for i , filename in enumerate (esa_files ):
63+ padded_count = get_padded_count (i + 1 , len (esa_files ))
64+ print ("{}/{}. Downloading file {}" .format (padded_count , len (esa_files ),
65+ os .path .basename (filename )))
66+
67+ download_path = dir / os .path .basename (filename )
68+ with open (download_path , 'wb' ) as download_file :
69+ download_file_obj = download_file
70+ total_byte_count = ftp .size (filename )
71+ read_byte_count = 0
72+ ftp .retrbinary ('RETR ' + filename , file_byte_handler , 1024 )
73+ download_path_list .append (download_path )
74+ print ("\n " )
75+ finally :
76+ print ("Exiting FTP." )
77+ ftp .quit ()
78+
79+ return download_path_list
0 commit comments