使用 Python 子进程执行 tar 命令不会在给定 --exclude 选项时排除某些文件

Executing tar command with Python subprocess does not exclude certain files when given --exclude option

我正在使用 python 子进程模块

执行下面的 tar 命令
import subprocess
cmd = ["/bin/tar", "-czf", "file.tar.gz", "./dir", "--exclude", "\"*cpp*\""]
subprocess.Popen(cmd)

但是没有排除 cpp 文件。

当我在 shell 提示符下 运行 相同的命令时,它工作正常。我做错了什么?

省略文字引号。即:

cmd = ["/bin/tar", "-czf", "file.tar.gz", "--exclude", "*cpp*", "./dir"]

否则,您只会排除名称以 " 开头和结尾的文件。


解释这是为什么:当你在 shell 中写 --exclude "*cpp*" 时,那些引号是 syntactic,而不是字面意思。他们告诉 shell 不要用文件列表替换 *cpp*;他们 没有 传递给 tar 他们自己。