gpt4 book ai didi

python - 为什么 python 子进程 zip 失败但在 shell 上运行有效?

转载 作者:太空狗 更新时间:2023-10-30 00:29:58 26 4
gpt4 key购买 nike

我在 Mac OS X 上使用 Python 2.7;使用 subprocess.callzip 失败,但在 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()(但将第一个参数设为以空格分隔的字符串)。

使用 glob.glob()可能是这里最好的选择:

import glob
import subprocess

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

关于python - 为什么 python 子进程 zip 失败但在 shell 上运行有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19585305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com