python實例:backup 備份
本文來源于《python簡明教程》中的實例
1.?提出問題: 我想要一個可以為我的所有重要文件創建備份的程序。
2. 分析明確問題:我們如何確定該備份哪些文件?備份保存在哪里?我們怎么樣存儲備份?
3. 設計程序列表:
1). 需要備份的文件和目錄由一個列表指定。
2). 備份應該保存在主備份目錄中。
3). 文件備份成一個zip文件。
4). zip存檔的名稱是當前的日期和時間。
4. 編寫代碼:
版本1:
#Filename: backup_ver1.py
importosimporttime#1. The files and directories to be backed up are specified in a list.
source = r'c:\python34'
#2. The backup must be stored in a main backup directory
target_dir = r'c:\python34\scripts' #Remember to change this to what you will be using
#3. The files are backed up into a rar file.#4. The name of the rar archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.rar'
#5. We use the rar command in windows to put the files in a zip archive,you must to be sure you have installed WinRARA and that in your path
rar_command = r'"C:\Program Files\WinRAR\WinRAR.exe" A %s %s -r' %(target,source)#Run the backup
if os.system(rar_command) ==0:
print ('Successful backup to',target)else:print ('Backup FAILED' )
分析:
1. ?注意,source、target_dir地址都可以你任意指定。source是指向的是需要備份的文件,target_dir指向的是需要保存的地址。
source = r'e:\code'target_dir= r'e:\code'
2.?zip archive壓縮文檔的名稱用target來指定; 其中運用了
加法操作符來級連字符串(即把兩個字符串連接在一起返回一個新的字符串);time.strftime()返回當前的時間;‘.rar’ 擴展名;
字符串join方法把source列表轉換為字符串。source可以換成‘’.join(source),貌似只能用這‘’,里面不能加入其它符號。
你一定要將WinRAR的路徑放到你的環境變量里面,然后才能直接使用WinRAR命令行。或者你要加上WinRAR的安裝路徑像這樣:
rar_command = r'"C:\Program Files\WinRAR\WinRAR.exe" A %s %s -r' % (target,source)
3. ?zip命令有一些選項和參數。??rar_command ="zip -qr '%s' %s"% (target,source)。
-q選項用來表示zip命令安靜地工作。 -r選項表示zip命令對目錄遞歸地工作,即它包括子目錄以及子目錄中的文件。兩個選項可以組合成縮寫形式-qr。所以自己查詢相關的幫助文檔。
但是自己在cmd命令行中輸入 zip可以查詢到相關的-q選項,可是沒有具體的實例。在ST3中輸入help('zip'),有內容,但是一點兒也沒幫助,查詢了python.doc文檔,用搜索檢索有zip模塊,但是里面的內容很多不相關,這怎樣查詢這個相關的幫助文檔呀? 還有在cmd中搜索 winrar卻沒有?
在cmd命令中有如下文檔說明,這有點像一種格式,
zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]
對應著:rar_command ="zip -qr '%s' %s"% (target,source)。其中 target 對應著[-b path] [-t mmddyyyy] [-n suffixes](注:suffixes 后綴 意思)
因為前面target指向的是壓縮文檔的名稱,包含了(目錄名+時間+后綴):target?=?target_dir?+?time.strftime('%Y%m%d%H%M%S')?+?'.rar'
所以[-options] 對應著 -qr,source對應著[zipfile list],那么[-xi list]對應著什么呢? 好像[-]這個表示可選項。
比如:
if os.system(XX命令) == 0:
print 'Successful!‘
那按以上這個例子,os.system命令應該返回0了,為什么?linux命令都是返回0代表成功,這是一個習慣,基本沒有人用返回值0代表命令失敗.所以 os.system(命令) 如果返回為0則帶便命令執行成功了.具體返回其他數值代表什么意思,就要看具體命令是什么了.比如最常用的 ls 命令, 有三個返回值:0 代表成功1 代表小問題2 代表大問題
你可以使用os.system(ls)試試。。這是linux系統。windows的話使用os.system(dir)試試
這個命令是執行系統命令的,這個命令在命令行下執行,返回的永遠是0。在窗口模式下,是所執行命令的返回值。
import os
cmd=r'c:\"Program Files"\notepad.exe c:\Program Files\1.txt'
os.system(cmd)
注意點:cmd中的命令的路徑出現空格需要用引號,后面的文件路徑不需要引號。
版本2:
關于zip
參考:python在windows下 完成文件備份的例子?: ? http://blog.csdn.net/qustdjx/article/details/7837619
補充:python執行系統命令的方法?os.system(),os.popen(),commands: ?http://blog.sina.com.cn/s/blog_5d24f0450101hc4w.html