2010-03-13 99 views
0
#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以及 - 任何人与备份目录的建议是非常值得欢迎Python脚本备份目录

+0

好的,我这样做(导入tarfile模块),它运行安静 - 我没有给任何消息,因为没有任何东西添加产生一条消息 - 我检查了位置destination = os.path.join(root,“文档和设置“,”rgolwalkar“,”桌面“,”桌面“,”PyDevResourse“)但没有找到备份。第二,如果我添加: - 如果os.system(tar)== 0:打印'成功备份到',targetBackup其他:打印'备份失败' - 如果os.system(tar)== 1出现错误:TypeError:system()参数1必须是字符串,而不是TarFile – rgolwalkar

+0

只是好奇,为什么你使用rar而不是跨平台的东西,比如zip,它被内置到python中? –

回答

0

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

为了避免这样的问题,使用subprocess模块,而不是os.system

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

也许不是写你自己的备份脚本可以使用名为rdiff进行备份蟒蛇的工具,它可以创造增量备份?

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

+0

非常感谢ghostdog74--让我检查代码并执行它 - 我将检查并粘贴O/P – rgolwalkar

+0

ghostdog74 - 我得到错误: - 回溯(最近一次调用最后一次): 文件“C:\ Documents and Settings \ rgolwalkar \ Desktop \ Desktop \ Dr Py \ Final_Py \ backup_ver1.py”,第16行,在 tar = tarfile.open(targetBackup,“w:gz”) NameError:name'tarfile '没有定义 – rgolwalkar

+0

tarfile是一个模块,导入它像'import tarfile' – ghostdog74