Python如何備份目錄及目錄下的全部內(nèi)容
就目錄拷貝的部分,思想很簡單。讀配置文件中的配置信息。
生成一個項目名稱加日期時間組成的文件夾名為分枝名稱。把當前項目下的全部內(nèi)容拷貝到這個目錄下。然后要做的研究就是調(diào)用TortoiseSVN命令嵌入這部分代碼。
現(xiàn)在看代碼:
1. 讀取配置文件
配置文件很簡單。用的就是txt文件。 格式類似于:
- # root:/Users/lichallenger/test_src/
- # project:test
- # destination:/Users/lichallenger/test_dst/
BTW: 我用的是Mac所以目錄格式是這樣的。如果你用的是Windows的話請適當修改配置文件。
讀文件就是最簡單的了。直接用標準庫的文件操作模塊打開文件,讀出全部的配置。一共就三行,所以也不用考慮效率什么的了。
- # open config file and read config information
- # author: bruce li
- class ConfigHandler(object):
- #
- def __init__(self,config_path):
- '''''initializer'''
- self.config_path = config_path
- #read config infor
- def read_config(self):
- f = open(self.config_path)
- try:
- self.all_lines = f.readlines()
- except:
- raise
- else:
- f.close()
2. 拷貝目錄和目錄內(nèi)容
拷貝目錄用了shutil模塊。里面有個方法可以直接把目錄和目錄下的全部內(nèi)容拷貝到制定的其他目錄。
這樣就省得搞目錄遍歷之類的代碼了。
- # copy dir(s) & file(s) to configured path
- # author: bruce li
- import shutil
- class CopyHandler(object):
- #
- def __init__(self,src_path,dest_path):
- self.src_path = src_path
- self.dest_path = dest_path
- def move_content(self):
- try:
- shutil.copytree(self.src_path,self.dest_path)
- except:
- raise
- @staticmethod
- def move_src_content(src, dest):
- try:
- shutil.copytree(src_path,dest_path)
- except:
- raise
3. 綜合調(diào)用
這里用了time模塊獲取當前時間,然后生成目標文件夾名稱的一部分。
外界給python傳的系統(tǒng)參數(shù)的***個是文件名。這個文件就相當于C#項目里的Program文件一樣,
里面會包含一個main函數(shù)。雖然這個函數(shù)不一定要命名為main。
- # main of dir copy function
- import sys
- import time
- from code_bk_cpy import *
- from code_bk_config import *
- #print __name__
- def main():
- config_path = sys.argv[1]
- # check if path of configuration path is empty
- if (not config_path):
- print 'configuration information is needed'
- return -1
- config_handler = ConfigHandler(config_path)
- config_handler.read_config()
- config_list = config_handler.all_lines
- if len(config_list) != 3:
- print 'configuration information is not correct'
- return -1
- # set source
- sep = ':'
- current_datetime = time.localtime(time.time())
- root_path = config_list[0].split(sep)[1]
- prj_name = config_list[1].split(sep)[1]
- dst_path = config_list[2].split(sep)[1]
- root_path = (root_path + prj_name).replace('\n','')
- prj_folder = prj_name + str(current_datetime.tm_year) + str(current_datetime.tm_mon) + \
- str(current_datetime.tm_mday) + str(current_datetime.tm_hour) + \
- str(current_datetime.tm_min) + str(current_datetime.tm_sec)
- dst_path = (dst_path + '/' + prj_folder + '/').replace('\n','')
- copy_handler = CopyHandler(root_path,dst_path)
- copy_handler.move_content()
- print 'content moved'
- # start main function
- print __name__
- if __name__ == "__main__":
- main()
還有注意下,Python代碼的換行符為\。
原文鏈接:http://www.cnblogs.com/sunshine-anycall/archive/2011/04/05/2005971.html
【編輯推薦】