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')


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