2013-10-25 39 views
4

我在使用Python 2.7的Mac OS X上;使用subprocess.callzip失敗,但在shell成功運行相同命令。這裏是我的終端的副本:爲什麼python subprocess zip失敗,但在shell中運行?

$ python 
Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import subprocess 
>>> subprocess.call(['zip', 'example.zip', 'example/*']) 
    zip warning: name not matched: example/* 

zip error: Nothing to do! (example.zip) 
12 
>>> quit() 
$ zip example.zip example/* 
    adding: example/file.gz (deflated 0%) 

我也嘗試過使用完整路徑並得到相同的結果。

+0

行爲取決於系統和適用於Windows,同時由於通過@MartijnPieters解釋 – alko

回答

6

因爲在shell中運行命令與使用subprocess.call()運行命令不同;該shell擴展了example/*通配符。

要麼自己擴展文件列表os.listdir()glob模塊,要麼通過Python的shell運行該命令;將shell=True參數設置爲subprocess.call()(但將第一個參數設置爲空白分隔的字符串)。

使用glob.glob()可能是這裏最好的選擇:

import glob 
import subprocess 

subprocess.call(['zip', 'example.zip'] + glob.glob('example/*')) 
0

嘗試殼=真。 subprocess.call('zip example.zip example/*',shell = True)會起作用。

+1

殼的理由* nix中失敗=真能引起安全問題,但它確實能夠使殼體通過; 'glob.glob'是更好的答案 – Zags

2

Martijn關於使用glob.glob的建議適用於通用shell通配符,但在這種情況下,它看起來好像要將目錄中的所有文件添加到ZIP歸檔文件中。如果這是正確的,你也許能夠使用-r選項zip

directory = 'example' 
subprocess.call(['zip', '-r', 'example.zip', directory]) 
+0

好的答案,但我認爲順序應該是'subprocess.call(['zip','-r','example.zip',directory])''。 –

+0

@shahar_m:好點!修正了,謝謝。 –

相關問題