为什么python subprocess zip失败但在shell上运行?

Nei*_*ski 5 python shell zip

我使用Python 2.7在Mac OS X上; 使用subprocess.callwith 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%)
Run Code Online (Sandbox Code Playgroud)

我也试过完整的路径并得到了相同的结果.

Mar*_*ers 11

因为在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/*'))
Run Code Online (Sandbox Code Playgroud)