Python: 在winXP系统下使用python正常调用zip命令

在做python练习的时候,有个例子是直接使用zip命令去备份一个文件,我是用WINXP系统,中间发生了很多问题,log下来做backup.

例子程序是这样的:
#!/usr/bin/python
#
 Filename: backup_ver1.py

import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte''/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

# 3. The files are backed up into a zip file.
#
 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S'+ '.zip'

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    
print 'Successful backup to', target
else:
    
print 'Backup FAILED'

由于上面例子是在Unix/Linux下的,需要改成windows
#!/usr/bin/python
#
 Filename: backup_ver1.py

import os
import time

source 
=[r'C:\My Documents', r'D:\Work']
target_dir 
= r'F:\back up\'     # Remember to change this to what you will be using
target 
= target_dir + time.strftime('%Y%m%d%H%M%S'+ '.zip'
zip_command 
= "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    
print 'Successful backup to', target
else:
    
print 'Backup FAILED'

问题一:
当改好后,运行会发生异常,提示:"EOL while scanning single-quoted string",该异常出现在上面代码的粗体行
target_dir = r'F:\back up\'
发生错误主要是因为转义符与自然符号串间的问题,看Python的介绍:
  • 自然字符串

    如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀rR来指定。例如r"Newlines are indicated by /n"

如上所说, target_dir的值应该被视作 'F:\back up\',可是这里的转义符却被处理了。如果换成 r'F:\\back up\\' 转义符却没被处理,于是target_dir的值变为'F:\\back up\\'.将单引号变成双引号,结果还是如此。而如果给它加中括号【】,变成【r'F:\back up\'】,则程序又没问题...

于是,解决方法有2个:1)如上所说,加中括号;2)不使用前缀r,直接用转义符‘\’,定义变成target_dir = 'F:\\back up\\'.

问题二:
解决完问题一后,运行module,会提示backup fail. 检查如下:
1. 于是试着将source和target字符串打印出来检验是否文件路径出错,发现没问题
2. 怀疑是windows没有zip命令,在命令行里打‘zip’, 却出现提示帮助,证明可以用zip命令,而且有参数q,r;
3. 想起sqlplus里命令不接受空格符,于是试着将文件名换成没空格的, module成功运行...

现在问题换成如何能让zip命令接受带空格路径,google了一下,看到提示:“带有空格的通配符或文件名必须加上引号
于是对 zip_command稍做修改

     
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
改成:
     zip_command = "zip -qr \"%s\" \"%s\"" % (target, '\" \"'.join(source))

改后,module成功运行...

正确的script应为:
Code

posted on 2009-08-18 15:15  炜升  阅读(1029)  评论(3编辑  收藏  举报