一個Python備份腳本
編寫一個Python腳本,實現為重要的文件或文件夾在指定的目錄下創建備份。
[設計思路]
[1] 將需要備份的文件和目錄由一個列表指定,通過傳入參數獲得并保存到列表中。
[2] 備份應該保存在主備份目錄中。
[3] 將文件備份成一個壓縮文件。
[4] 每一次備份都根據當前的日期在主備份目錄中創建一個子文件夾,而所備份的文件命名為當期的時間保存在這個子文件夾中。
[5] 壓縮命令由本地用戶決定。可以使用任何本地的存檔壓縮命令,只要它有命令行界面就可以了,那樣就可以從腳本中傳遞參數給它。
[參考]
[1]
A Byte of Python, 2005
[2]
Python Manuals 2.6
#! /usr/bin/python# Filename: backup_ver1.py # 2010-7-12 wcdj import os import time import sys # 1, The files and directories to be backed up are specified in a list # source = ['/home/wcdj/my_prog', '/home/wcdj/local_installed'] # The following information is the debug used print '--------------------------------' source=[] print 'The command line arguments are: ' for i in sys.argv: print i if i == sys.argv[0]: continue source.append(i) print source print '--------------------------------' # check input, if error app exit if len(source) == 0: print '''''You should input the files or directories, like python backup_ver1.py /home/wcdj/myfile /home/wcdj/mydir ...''' exit() else: print 'Some files or directorier will be saved into .tar.gz format: ' print source # If you are using Windows, use # source=[r'c:/Documents', r'd:/work'] or # source=['c://Documents', 'd://work'] or # something like that # 2, The backup must be stored in a main backup directory # Remember to change this to what you will be using target_dir = '/home/wcdj/backup/' # 3, The files are backed up into a tar file # 4, The name of subdirectory and tar file today = target_dir + time.strftime('%Y%m%d') now = time.strftime('%H%M%S') # Take a comment from the user to create the name of the tar file comment = raw_input('Enter a comment: ') if len(comment) == 0:# check if a comment was entered target = today + os.sep + now + '.tar.gz' else: target = today + os.sep + now + '_' + / comment.replace(' ', '_') + '.tar.gz' #Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today)# make directory print 'Successfully created directory', today # 5, We use the tar command(in Unix/Linux) to put the files in a tgz archive tar_command = "tar -zcf %s %s" % (target, ' '.join(source)) # Run the backup if os.system(tar_command) == 0: print 'Successful backup to', target else: print 'Backup failed' # end </pre>
本文由用戶 ydn7 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!