Python調用zip命令正確操作方法解析
當我們在應用Python編程語言進行程序開發的時候,我們會發現這一語言可以幫助我們輕松的完成一些特定的功能需求。在這里我們就先一起來了解一下Python調用zip命令的使用方法,以此了解這一語言的操作方法。
Python調用zip命令例子程序是這樣的:
- #!/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'
由于上面Python調用zip命令例子是在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調用zip命令中,發生錯誤主要是因為轉義符與自然符號串間的問題,看Python的介紹:#t#
自然字符串
如果你想要指示某些不需要如轉義符那樣的特別處理的字符串,那么你需要指定一個自然字符串。自然字符串通過給字符串加上前綴r或R來指定。例如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應為:
- #!/usr/bin/Python
- # Filename: backup_ver1.py
- import os
- import time
- source =[r'C:\My Documents', r'D:\Work']
- target_dir = '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'
以上就是我們對Python調用zip命令的相關介紹。