Created
June 6, 2013 03:50
-
-
Save ivan-krukov/5719182 to your computer and use it in GitHub Desktop.
Complete download file over FTP example. Complete with write-report closure in python3 style, writing stdout to same line and nice verbosity handling
This file contains hidden or 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
#!/usr/bin/env python3 | |
from ftplib import FTP | |
def ftp_download(server,remote_path,local_path,username="anonymous",password="",verbose=True): | |
#new ft object | |
ftp = FTP(server) | |
if verbose: print("Connected to %s"%server) | |
#notice that default login is "anonymous" with no password. works on most public servers | |
ftp.login(username,password) | |
if verbose: print("Logged in as %s"%username) | |
#get size of the desired file | |
size = ftp.size(remote_path) | |
if verbose: print("Download size %sb"%size) | |
#measure download progress | |
downloaded = 0.0 | |
chunksize = 8192 | |
with open(local_path,"wb") as output_file: | |
#python3 style closure using nonlocal keyword to grab parental values | |
def _dl_write(chunk): | |
nonlocal size | |
nonlocal downloaded | |
nonlocal chunksize | |
output_file.write(chunk) | |
downloaded+=chunksize | |
#end="\r" allows us to overwrite the output on the same line | |
print("%.1f%%"%(downloaded/size*100),end="\r") | |
if verbose: print("Downloading %s"%remote_path) | |
ftp.retrbinary("RETR %s"%remote_path,callback = _dl_write) | |
print("Done") | |
ftp.quit() | |
def main: | |
ftp_download("ftp.example.com","path/to/remote/file","path/to/local/file") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment