Python简明教程中压缩存档例子:正常调用压缩命令(Windows系统下)

注:原文为转载,对于不好理解的源代码部分进行了修改,直接以改进后的代码进行替换,可能与原文不同。


Python3.3:正常调用压缩命令(Windows系统下)
在《python简明教程》(下载地址:http://wenku.baidu.com/view/0c4e5df5f61fb7360b4c658c.html)学习的过程中,例10.1 备份脚本——版本一,中的代码是以Linux为背景。而我正在学习Python3.3,并以windowsXP为背景。
以下为《python简明教程》中,例10.1的源代码:
---------------------------------------------------------------------------------------------------
#!/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'
---------------------------------------------------------------------------------------------------
os.system函数 运行 命令,利用这个函数就好像在 系统 中运行命令一样。即在shell中运行命令——如果命令成功运行,它返回0,否则它返回错误号。
其中以zip_command字符串为重点,它包含我们将要执行的命令。你可以在shell(Linux终端中)运行它,以检验它是否工作。这是因为linux自带zip软件。但在Windows系统中的DOS命令行中不一定能执行。Windows中大部分人都使用Winrar这个软件,我们下面以WinRAR代替Linux下的zip。

首先,为了能在命令行直接运行“rar”命令,我们做一个拷贝操作:

拷贝D:\Program Files\WinRAR目录下的Rar.exe这个文件(可以看到提示为"命令行 RAR“)到当前系统的C:\WINDOWS\system32目录下,可以把这个操作理解为注册环境变量的操作。之后你在cmd下输入rar,回车,应该就能看到提示了,如下图所示:



好了,下面是我们的python代码,注意版本很重要,不同的版本一些基本函数的用法都会不同,比如print。

# !/usr/bin/python
# Filename: backup_ver2.py

import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = r'D:\Work'
# 2. The backup must be stored in a main backup directory
target_dir = 'D:\\'
# 3. The fiels 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') + '.rar'

# 5. We use the zip command to put the files in a zip archive
#zip_command = "zip -qr  '%s'    %s"     %   (target,    ''.join(source))
#rar_command = 'rar a{0} {1}'.format(target,source)
rar_command = "rar a %s %s"%(target,''.join(source))
#rar_command= '"C:\Program Files\WinRAR\WinRAR.exe" a %s %s'%(target,' '.join(source))
# Run the backup
#if os.system(zip_command) == 0:     
if os.system(rar_command) == 0:
    print('Successful backup to'), target
else:
    print('Backup FAILED')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章