用于备份目录的Python脚本
winrar也被添加到环境变量下的Path和CLASSPATH中-任何对备份目录有建议的人都是最受欢迎的源目录包含空格,但在命令行中没有引号。这可能是备份失败的原因之一 要避免此类问题,请使用模块而不是操作系统用于备份目录的Python脚本,python,windows-xp,backup,rar,Python,Windows Xp,Backup,Rar,winrar也被添加到环境变量下的Path和CLASSPATH中-任何对备份目录有建议的人都是最受欢迎的源目录包含空格,但在命令行中没有引号。这可能是备份失败的原因之一 要避免此类问题,请使用模块而不是操作系统os.system: #Filename:backup_ver1 import os import time #1 Using list to specify the files and directory to be backed up source = r'C:\Documents
os.system
:
#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
也许您可以使用名为rdiff backup的python工具来创建增量备份,而不是编写自己的备份脚本?如果压缩算法可以是其他算法,而只是备份一个目录,为什么不使用python自己的tar和gzip呢?乙二醇
subprocess.call(['rar.exe', 'a', '-ag', targetBackup, source])
这样,您就不需要依赖系统上的
rar.exe
。非常感谢ghostdog74--让我检查代码并以这种方式执行--我将检查并粘贴O/Pghostdog74--我得到错误:-回溯(最后一次调用):文件“C:\Documents and Settings\rgolwalkar\Desktop\Desktop\Dr Py\Final\u Py\backup\ver1.Py”,第16行,tar=tarfile.open(targetBackup,“w:gz”)name错误:名称“tarfile”未定义tarfile是一个模块,像导入tarfile一样导入它import tarfileok我这样做了,它安静地运行了--我没有给出任何消息,因为没有添加任何内容来生成消息-我检查了位置destination=os.path.join(root,“文档和设置”、“rgolwalkar”、“Desktop”、“Desktop”、“PyDevResourse”),但找不到备份。第二个如果我添加:-如果os.system(tar)=0:打印“成功备份到”,则targetBackup否则:打印“备份失败”--如果os.system(tar)=1:TypeError:system()参数1必须是字符串,而不是tarfile为什么使用os.system
?tar
是unix命令。如果使用os.system(tar)
,实际上您正在调用tar命令。Python脚本中的tar
只是tarfilemodule
的实例,而不是tar
命令。输入一些打印语句并确保目录路径正确。我在*nix上可以正常工作。好的,我这样做了(导入了tarfile模块)它安静地运行——我没有给出任何消息,因为没有添加任何内容来生成消息——我检查了位置destination=os.path.join(root,“Documents and Settings”,“rgolwalkar”,“Desktop”,“Desktop”,“PyDevResourse”),但没有找到备份。第二,如果添加:-if os.system(tar)==0:print'Successful backup to',targetBackup else:print'backup FAILED',如果os.system(tar)==1:TypeError:system()参数1必须是字符串,而不是tarfile,那么会出现一个错误。奇怪的是,为什么要使用rar而不是跨平台的东西,比如python内置的zip?
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()