Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么python子流程zip失败,但在shell works上运行?_Python_Shell_Zip - Fatal编程技术网

为什么python子流程zip失败,但在shell works上运行?

为什么python子流程zip失败,但在shell works上运行?,python,shell,zip,Python,Shell,Zip,我在MacOSX上使用Python2.7;使用subprocess.call和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 "lic

我在MacOSX上使用Python2.7;使用
subprocess.call
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%)

我也尝试过使用完整路径,得到了相同的结果。

因为在shell中运行命令与使用
subprocess.call()运行命令是不同的;shell扩展了
example/*
通配符

使用
os.listdir()
glob
模块自己展开文件列表,或者通过Python中的shell运行命令;使用
shell=True
参数调用
subprocess.call()
(但将第一个参数设置为空格分隔的字符串)

在这里,使用可能是最好的选择:

import glob
import subprocess

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

试试shell=True。subprocess.call('zip example.zip example/*',shell=True)可以工作

Martijn的建议适用于一般的shell通配符,但在本例中,您似乎希望将目录中的所有文件添加到ZIP存档中。如果是这样,您可以使用
-r
选项:


行为依赖于系统并在Windows上工作,而在*nix上由于@martijnpietershell=True解释的原因而失败可能会导致安全问题,但它确实会启用shell全局绑定
glob.glob
是一个更好的答案很好的答案,但我认为顺序应该是
subprocess.call(['zip','-r',example.zip',directory])
。我们为什么不在python中使用模块呢。这两种方法之间有什么区别吗?@C.R.Sharat:问题是为什么glob没有被扩展。您必须询问OP为什么他们更喜欢使用命令行工具而不是Python模块。
directory = 'example'
subprocess.call(['zip', '-r', 'example.zip', directory])