用于备份目录的Python脚本

时间:2010-03-13 10:45:01

标签: python windows-xp backup rar

#Filename:backup_ver1

import os
import time

#1 Using list to specify the files and directory to be backed up
source = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\Dr Py\Final_Py'

#2 define backup directory
destination = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\PyDevResourse'

#3 Setting the backup name
targetBackup = destination + time.strftime('%Y%m%d%H%M%S') + '.rar'

rar_command = "rar.exe a -ag '%s' %s" % (targetBackup, ''.join(source))
##i am sure i am doing something wrong here - rar command please let me know

if os.system(rar_command) == 0:
    print 'Successful backup to', targetBackup
else:
    print 'Backup FAILED'

O/P:- Backup FAILED

winrar也被添加到环境变量下的Path和CLASSPATH中 - 其他任何有建议备份目录的人都非常欢迎

3 个答案:

答案 0 :(得分:2)

也许不是编写自己的备份脚本而是使用名为rdiff-backup的python工具,它可以创建增量备份吗?

答案 1 :(得分:0)

source目录包含空格,但在命令行中没有引号。这可能是备份失败的原因。

要避免此类问题,请使用subprocess模块而不是os.system

subprocess.call(['rar.exe', 'a', '-ag', targetBackup, source])

答案 2 :(得分:0)

如果压缩算法可以是其他东西并且只是为了备份目录,为什么不用python自己的tar和gzip呢?例如

import os
import tarfile
import time
root="c:\\"
source=os.path.join(root,"Documents and Settings","rgolwalkar","Desktop","Desktop","Dr Py","Final_Py")
destination=os.path.join(root,"Documents and Settings","rgolwalkar","Desktop","Desktop","PyDevResourse")
targetBackup = destination + time.strftime('%Y%m%d%H%M%S') + 'tar.gz'    
tar = tarfile.open(targetBackup, "w:gz")
tar.add(source)
tar.close()

这样,您就不依赖于系统上的rar.exe