在Windows平台下实现《简明 Python 教程》第十章案例(利用winrar实现压缩备份)...

在《简明Python教程》第十章,作者以一个小的脚本开发作为案例讲解Python(http://woodpecker.org.cn/abyteofpython_cn/chinese/ch10s02.html

但是该案例在Windows平台下运行会失败,作者也一笔带过没有多讲,在此改写一下使之在Windows平台可以顺利运行

除了作者已经在文章中提到的转义符问题(详见文中“给Windows用户的注释”)

主要问题出现在

1 zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

而在Windows下不支持zip命令行进行压缩,在此需要借用其他外部程序(如WinRAR。我试了下360zip,不过据说其还没开发出命令行操作,所以我使用时暂时不行,如有使用360zip成功的网友可以跟帖).

1.安装WinRAR

2.将WinRAR的路径放到环境变量里(右键单击计算机->属性->高级系统属性->环境变量->系统变量,找到Path进行编辑,就是在最后一行加上WinRAR的安装目录,例如安装目录在C:\WinRAR,所以添加;C:\WinRAR)

可以进入DOS进行测试(在命令行中输入 rar,如果返回很多用法就是没问题的)

3.改写zip_command

1 zip_command="rar a %s %s " %(target, ' '.join(source))

理论上运行不会出问题了,完整代码如下

完整代码
 1 #!/usr/bin/env python
 2 # Filename: backup_ver1.py
 3 
 4 import os
 5 import time
 6 
 7 # 1. The files and directories to be backed up are specified in a list.
 8 source=[r'C:\source',r'C:\source_test']
 9 
10 # If you are using Windows, use source=[r'C:\Documents',r'D:\Work'] or something like that
11 
12 # 2. The backup must be stored in a main backup directory
13 target_dir=r'C:\target\\'
14 #Remember to change this to what you will be using
15 
16 # 3. The files are backed up into a zip file
17 # 4. The name of the zip archive is the current date and time
18 target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.zip'
19 
20 # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
21 zip_command="rar a %s %s " %(target, ' '.join(source))
22 
23 
24 # Run the backup
25 if os.system(zip_command)==0:
26     print 'Successful backup to',target
27 else:
28     print 'Backup FAILED'

其中

1 target_dir=r'C:\target\\'

之所以后面有两个 \\ 是为了防止备份时将target作为名称而不是路径,当然也可以文件命名一行这样改

1 target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S')+'.rar'

转载于:https://www.cnblogs.com/jessechen/archive/2012/09/12/2682374.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值