Python enables green software upgrades, including single-file upgrades and multi-file upgrades

Source: Internet
Author: User
Tags create zip create zip file tmp file

# coding:utf-8import sys, OS, timeimport zipfileimport shutildef print_usage (): print "' Usage:python Software_upgrad            e.py Subzipfullpath, Targetzipfullpath, mainversionzippath[, relativepath]\n for Example:linux platform: Python software_upgrade.py/test/software_upgrade/subversiondir/readme.txt/test/software_upgrade/ Latestversiondir/myapp_latest.zip/test/software_upgrade/mainversiondir/myapp_main.zip/readme.txt python softw are_upgrade.py/test/software_upgrade/subversiondir/myapp_subversion_0.1.zip/test/software_upgrade/            Latestversiondir/myapp_latest.zip/test/software_upgrade/mainversiondir/myapp_main.zip Windows Platform: Python software_upgrade.py C:\software_upgrade\subVersionDir\readme.txt C:\software_upgrade\latestVersionDir\ Myapp_latest.zip C:\software_upgrade\mainVersionDir\myAPP_main.zip \readme.txt python software_upgrade.py C:\so Ftware_upgrade\subversiondir\myapp_subversion_0.1.zip C:\software_upgrade\latesTversiondir\myapp_latest.zip C:\software_upgrade\mainVersionDir\myAPP_main.zip "def my_copytree (SRC, DST, Symlinks=false): "" If the same target already exists then do not move Args:src:dst:symlinks:Returns: "" "names = OS . Listdir (SRC) if not os.path.isdir (DST): Os.makedirs (DST) errors = [] for name in Names:srcname = Os.path.join (SRC, name) DstName = Os.path.join (DST, name) Try:if symlinks and Os.path.islink (src Name): Linkto = Os.readlink (srcname) os.symlink (Linkto, dstname) elif OS.PATH.ISD IR (srcname): My_copytree (SrcName, DstName, symlinks) else:if Os.path.isdir (Dstna Me): Os.rmdir (DstName) elif os.path.isfile (dstname): Os.remove (Dstnam        e) shutil.copy2 (SrcName, DstName) # XXX What about devices, sockets etc.? Except (IOError, Os.error) as Why:erroRs.append ((SrcName, DstName, str)) # Catch the Error from the recursive copytree so we can # Conti Nue with other files except OSError as Err:errors.extend (Err.args[0]) Try:shutil.copystat (SR        C, DST) except Windowserror: # can ' t copy file access times on Windows pass except OSError as why: Errors.extend (SRC, DST, str (why))) if Errors:pass # raise Error (Errors) def unzip (filename, Filedir) : "" "Args:filename: ' Foobar.zip ' #要解压的文件 filedir: The directory Returns after decompression:" "R = Zipfile.is_zip File (filename) If r:starttime = Time.time () FZ = ZipFile. ZipFile (filename, ' r ') for file in Fz.namelist (): # print (file) # Prints the directory in the ZIP archive fz.extract (file , filedir) Endtime = Time.time () times = Endtime-starttime Else:print (' This file was not zip fil E ') print (' [Unzip file] time costs: ' + str ') def zip (path, fileName): "" By default, zip compression retains the root directory, we do not keep the root directory Args:path: The document directory to be compressed filename: ' foobar.zip ' # compressed file name Returns: "" "try:import zlib compression = ZipFile. Zip_deflated # compression Method except:compression = ZipFile. zip_stored starttime = Time.time () # start = Path.rfind (os.sep) + 1 # Os.sep delimiter (retains root) start = Len (path) # ( Do not retain the root directory) z = zipfile.            ZipFile (filename, mode= "w", Compression=compression) try:for Dirpath, dirs, files in Os.walk (path): For file in files:if file = = FileName or file = = "zip.py": Continue # PR int (file) Z_path = Os.path.join (dirpath, file) z.write (Z_path, Z_path[start:]) Z.clos E () Endtime = Time.time () times = Endtime-starttime except:if z:z.close () print ( ' [Create zip file] Time costs: ' + str (times) ' Def create_latest_package (Subversionfullpath, LatestversionfullpatH, Mainversionfullpath, RelativePath): "" "Args:subVersionFullPath:latestVersionFullPath:latest_Zip _path mainVersionFullPath:relativePath:Returns: "" "If Os.path.exists (Subversionfullpath) and OS. Path.exists (Mainversionfullpath): # Determine if the child version and the main version of the ZIP package exist if not os.path.exists (Latestversionfullpath): # If The latest version of the ZIP package does not exist, assemble the latest file of the child version with the main version of the file, and then compress the assembled file to the directory where the latest version is located oper (Subversionfullpath, Mainversionfullpath, latestve            Rsionfullpath, RelativePath) Else: # If the latest version of the ZIP package is present, assemble the latest file of the child version with the latest version of the file, and then compress the assembled file to the directory where the latest version is located Oper (Subversionfullpath, Latestversionfullpath, Latestversionfullpath, RelativePath) Else:print "not exists { 0} or {1} ". Format (Subversionfullpath, Mainversionfullpath) def oper (Srvzippath, Destzippath, Outzippath, RelativePath) : "" "Note: When multiple files are replaced, generally many files exist in the compressed package, so need to decompress the basic idea 1. Unzip the latest version of the zip file into the same TMP directory as 2. If a single file upgrade, copy the child version of the file to the TMP directory in the 1 step;     is a multi-file upgrade, you first need to extract multiple files and then copy       3. Re-compress the TMP file after step 2 and place it in the new version Args:srvzippath: Child version Zip path destzippath: Target version zip path Outzippath:    After assembling, the full path to generate a new zip file RelativePath: Single file and multi-file ID, if none indicates multiple file substitution, otherwise the single file replaces Returns: "" "# If the path to the resulting zip file does not exist, create    Outzippathdir = Os.path.dirname (Outzippath) os.makedirs (outzippathdir) if not os.path.exists (outzippathdir) Else ' # Determine the path of the temporary file Srvzippathtmp = Os.path.dirname (srvzippath) + os.sep + "tmp" destzippathtmp = Os.path.dirname (destzip Path) + os.sep + "tmp" print "[unzip target zip] srv:{0} dest:{1}". Format (Destzippath, destzippathtmp) unzip (Destz Ippath, Destzippathtmp) # Unzip the target zip file if relativepath: # Single file and multi-file ID, if none indicates multiple file substitution, otherwise the single file replaces print "  Place] srv:{0} dest:{1} ". Format (Srvzippath, destzippathtmp + relativepath) shutil.copy (Srvzippath, destzippathtmp + relativepath) # Copy the file you want to upgrade to a target zip file that has been unpacked destzippathtmp else:print "[Unzip source zip] srv:{0} dest:{1}". f Ormat (Srvzippath, SrvzipPATHTMP) Unzip (Srvzippath, srvzippathtmp) print "[Replace files] srvzippathtmp:{0} destzippathtmp:{1}". fo Rmat (srvzippathtmp, destzippathtmp) my_copytree (srvzippathtmp, destzippathtmp) # Copy the file you want to upgrade to a target zip file that has been unpacked Destzippat Htmp in print "[Create new Zip file] srv:{0} dest:{1}". Format (destzippathtmp, Outzippath) Zip (destzippathtmp, Outzip Path) # Delete temporary file Shutil.rmtree (srvzippathtmp) if os.path.exists (srvzippathtmp) Else ' Shutil.rmtree (destzippathtmp If Os.path.exists (destzippathtmp) Else ' print ' success "if __name__ = = ' __main__ ': number = 0 for i in Sys.arg        V:print "Arg{0}: {1}". Format (number, i) number + = 1 if len (SYS.ARGV) < 4 or len (SYS.ARGV) > 5: Print_usage () If Len (sys.argv) = = 4:create_latest_package (sys.argv[1], sys.argv[2], sys.argv[3], None) E Lif len (sys.argv) = = 5:create_latest_package (sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])

  

Python enables green software upgrades, including single-file upgrades and multi-file upgrades

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.