Python中的备份脚本

时间:2011-02-05 11:10:46

标签: python unix

有些人可以向我提供代码的解释,特别是在“for f in files:”行之后使用maxversions和语句。

我想了解xrange(MAXVERSION)的含义是什么?索引的用途是什么,即

for index in xrange(MAXVERSIONS): backup = '%s.%2.2d' % (destpath, index) 

代码:

!/usr/bin/env python

import sys,os, shutil, filecmp

MAXVERSIONS=100
BAKFOLDER = '.bak'

def backup_files(tree_top, bakdir_name=BAKFOLDER):

     top_dir = os.path.basename(tree_top)
    tree_top += os.sep

    for dir, subdirs, files in os.walk(tree_top):

        if os.path.isabs(bakdir_name):
            relpath = dir.replace(tree_top,'')
            backup_dir = os.path.join(bakdir_name, top_dir, relpath)
        else:
            backup_dir = os.path.join(dir, bakdir_name)

        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)

            subdirs[:] = [d for d in subdirs if d != bakdir_name]
        for f in files:
            filepath = os.path.join(dir, f)
            destpath = os.path.join(backup_dir, f)
                for index in xrange(MAXVERSIONS):
                backup = '%s.%2.2d' % (destpath, index)
                abspath = os.path.abspath(filepath)

                if index > 0:

                    old_backup = '%s.%2.2d' % (destpath, index-1)
                    if not os.path.exists(old_backup): break
                    abspath = os.path.abspath(old_backup)

                    try:
                        if os.path.isfile(abspath) and filecmp.cmp(abspath, filepath, shallow=False):
                            continue
                    except OSError:
                        pass

                try:
                    if not os.path.exists(backup):
                        print 'Copying %s to %s...' % (filepath, backup)
                        shutil.copy(filepath, backup)
                except (OSError, IOError), e:
                    pass

if __name__=="__main__":
    if len(sys.argv)<2:
        sys.exit("Usage: %s [directory] [backup directory]" % sys.argv[0])

    tree_top = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[1])))

    if len(sys.argv)>=3:
        bakfolder = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[2])))
    else:
        bakfolder = BAKFOLDER

    if os.path.isdir(tree_top):
        backup_files(tree_top, bakfolder)

1 个答案:

答案 0 :(得分:3)

脚本尝试递归地将目录的内容(默认为当前目录)复制到备份目录(当前目录中默认为.bak);

对于每个filename.ext,它创建一个名为filename.ext.00的副本;如果filename.ext.00已经存在,则会创建filename.ext.01,依此类推。

xrange()是一个生成器,它返回0 ..(MAXVERSION-1)中的所有数字,因此MAXVERSION控制要尝试的版本后缀的数量,即要保留多少旧版本的文件。