您的位置:首页 > 运维架构 > Linux

linux下python学习笔记(十四)之备份实例2

2013-04-29 21:06 1056 查看
接着上篇进行改进。

版本三

第二个版本在我做较多备份的时候还工作得不错,但是如果有极多备份的时候,我发现要区分每个备份是干什么的,会变得十分困难!例如,我可能对程序或者演讲稿做了一些重要的改变,于是我想要把这些改变与zip归档的名称联系起来。这可以通过在zip归档名上附带一个用户提供的注释来方便地实现。

备份脚本——版本三

#!/usr/bin/python

# Filename: backup_ver3.py

import os

import time

# 1. The files and directories to be backed up are specified in a list.

source =['/home/li/hello.cpp', '/home/li/new/aa']

# 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/backup1/' # 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'

# 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'



对于大多数用户来说,这个版本是一个满意的工作脚本了,但是它仍然有进一步改进的空间。比如,你可以在程序中包含 交互 程度——你可以用-v选项来使你的程序更具交互性。另一个可能的改进是使文件和目录能够通过命令行直接传递给脚本。我们可以通过sys.argv列表来获取它们,然后我们可以使用list类提供的extend方法把它们加到source列表中去。我还希望有的一个优化是使用tar命令替代zip命令。这样做的一个优势是在你结合使用tar和gzip

命令的时候,备份会更快更小。如果你想要在Windows中使用这些归档,WinZip也能方便地处理这些.tar.gz文件。tar命令在大多数Linux/Unix系统中都是默认可用的。Windows用户也可以下载安装它。

命令字符串现在将称为:

tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir))

选项解释如下:

● -c表示创建一个归档。

● -v表示交互,即命令更具交互性。

● -z表示使用gzip滤波器。

● -f表示强迫创建归档,即如果已经有一个同名文件,它会被替换。

● -X表示含在指定文件名列表中的文件会被排除在备份之外。例如,你可以在文件中指定

*~,从而不让备份包括所有以~结尾的文件。

最理想的创建这些归档的方法是分别使用zipfile和tarfile。它们是Python标准库的一部分,可以供你使用。使用这些库就避免了使用os.system这个不推荐使用的函数,它容易引发严重的错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: