python教程在例10.4 備份腳本的代碼的介紹
python教程在例10.4 備份腳本——版本四的代碼是相當(dāng)長的,所以很多人對其有束手無策之感,但是你通過以下的代碼對其,有更好的了解,以下就是相關(guān)內(nèi)容的詳細(xì)介紹。希望你會有所收獲。
- #!/usr/bin/python
- # Filename: backup_ver4.py
- import os
- import time
- # 1. The files and directories to be backed up are
specified in a list.- source = [‘/home/swaroop/byte’, ‘/home/swaroop/bin’]
- # If you are using Windows, use source =
[r'C:\Documents'
, r'D:\Work'] or something like that- # 2. The backup must be stored in a main backup
directory- target_dir = ‘/mnt/e/backup/’ # Remember to change
this to what you will be using- # 3. The files are backed up into a zip file.
- # 4. The current day is the name of the
subdirectory in the main directory- today = target_dir + time.strftime(‘%Y%m%d’)
- # The current time is the name of the zip archive
- now = time.strftime(‘%H%M%S’)
- # Take a comment from the user to create the name
of the zip file- comment = raw_input(‘Enter a comment –> ‘)
- if len(comment) == 0: # check if a comment was entered
- target = today + os.sep + now + ‘.zip’
- else:
- target = today + os.sep + now + ‘_’ + \
- comment.replace(‘ ‘, ‘_’) + ‘.zip’
- # Notice the backslash!
- # 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 zip command (in Unix/Linux) to put the
files in a zip archive- zip_command = "zip -qr ‘%s’ %s" % (target, ‘
‘.join(source))- # Run the backup
- if os.system(zip_command) == 0:
- print ‘Successful backup to’, target
- else:
- print ‘Backup FAILED’
文中提到“我還希望有的一個優(yōu)化是使用tar命令替代zip命令。這樣做的一個優(yōu)勢是在你結(jié)合使用tar和gzip命令的時候,備份會更快更小。如果你想要在Windows中使用這些歸檔,WinZip也能方便地處理這些.tar.gz文件。tar命令在大多數(shù)Linux/Unix系統(tǒng)中都是默認(rèn)可用的。Windows用戶也可以下載安裝它。命令字符串現(xiàn)在將成為:
- tar = ‘tar -cvzf %s %s -X /home/swaroop/
excludes.txt’ % (target, ‘ ‘.join(srcdir))
需要補(bǔ)充的是Windows用戶安裝完LibArchive后命令為bsdtar,而且若想使用-z這個選項,還需安裝gzip軟件。代碼中的
- target = today + os.sep + now + ‘.zip’
改為
- target = today + os.sep + now + ‘.tar.gz’
使用
- bsdtar -cvzf %s %s -X /home/swaroop/
excludes.txt’ % (target, ‘ ‘.join(source))
以上的內(nèi)容就是對簡明python教程在例10.4 備份腳本——版本四的代碼中有些需要注意的地方的詳細(xì)介紹。
【編輯推薦】