#!/usr/bin/env python # -*- coding: utf8 -*- # ftp下载、解压、更新依赖库文件 import os, sys, stat, shutil, string, zipfile, ftplib from urlparse import urlparse # list of depended libraries urllist = [ "ftp://1.2.3.4/foo.zip", "ftp://1.2.3.4/bar.zip" ] def remove_old(lst) : print "cleaning libraries..." for url in lst : try : dirname = os.path.splitext(os.path.split(urlparse(url).path)[1])[0] print "cleaning [%s]..." % (dirname) shutil.rmtree(dirname) print "[%s] cleaned." % (dirname) except Exception, e : continue print "libraries cleaned." pass def ftp_download(host, port, username, password, ftpdir, zipname) : try : print "downloading file [%s]..." % (zipname) hftp = ftplib.FTP() hftp.connect(host, port) hftp.login(username, password) hftp.cwd("/") hftp.cwd(ftpdir) fp = open(zipname, "wb") hftp.retrbinary("RETR " + zipname, fp.write) hftp.close() fp.close() except Exception, e : print "downloading file [%s] failed, err %s." % (zipname, e) return -1 print "file [%s] downloaded." % (zipname) return 0 pass def unzip(zipname, path) : try : print "unziping file [%s]..." % (zipname) os.mkdir(path) zf = zipfile.ZipFile(zipname, "r") zf.extractall(path) zf.close() os.remove(zipname) except Exception, e : print "unziping file [%s] failed." % (zipname) return -1 print "file [%s] unziped." % (zipname) return 0 pass def get_lib(url) : print "getting library [%s]..." % url tp = urlparse(url) host = tp.netloc path = tp.path [ftpdir, zipname] = os.path.split(path) localdir = os.path.splitext(zipname)[0] [port, username, password] = [21, "anonymous", "anonymous"] ret = ftp_download(host, port, username, password, ftpdir, zipname) if ret != 0 : print "getting library [%s] failed." % url return -1 ret = unzip(zipname, localdir) if ret != 0 : print "getting library [%s] failed." % url return -1 print "library [%s] got." % url return 0 pass def update_libs(lst) : print "updating libraries..." for url in lst : ret = get_lib(url) if ret != 0 : print "updating libraries failed." return print "libraries updated." pass # main if __name__ == "__main__" : print "depended libraries:" for url in urllist : print "\t[%s]" % url print "========================================" remove_old(urllist) update_libs(urllist) pass
简单起见,没有把依赖库列表和代码分开,自定义依赖库直接改代码中的 url 数组即可。