Python 编写通过DOS压缩的例子遇到的几个问题

 在完成backup_ver1.py的例子是,遇到了几个问题。

1.教程上是用zip进行压缩,而本机未安装zip,DOS无法执行zip命令。

Solved:换用rar命令执行,其中将C:/Program Files/WinRAR下的Rar.exe拷贝到%SystemRoot%/system32下,这样你就不必设置rar的环境变量,而能直接再cmd 命令提示符下使用rar命令 .

    其中rar压缩命令为  rar a filesname.rar filesname

参考http://blog.csdn.net/jianzhiying/article/details/5407579

或http://www.cnblogs.com/monkeyfather/p/4160142.html

2.用作范例的文件夹路径中包含空格,DOS无法正确识别压缩路径。

Solved:在构成压缩路径是,在路径前后添加“”字符,注意用‘”’转义符。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename:backup_ver1.py

__author__ = 'JerryQiu'

import os
import time

source = ['"E:\My Files\Baby"']

target_dir = 'E:\My Files\'

target ='"' + target_dir + time.strftime('%Y%m%d') + '.rar' + '"'

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

print rar_command

if os.system(rar_command) == 0:
    print 'Successful backup to', target

else:
    print 'Backup Failed'

  

原文地址:https://www.cnblogs.com/monkeyfather/p/4160241.html