Python 脚本不会从存档中删除文件 -- 通过终端打印的命令工作正常

Python script doesn't delete file from archive -- printed command via terminal works fine

我正在 Python 使用此代码创建存档:

#Creates archive using string like [proxy_16-08-15_08.57.07.tar]
proxyArchiveLabel = 'proxy_%s' % EXECUTION_START_TIME + '.tar'
log.info('Packaging %s ...' % proxyArchiveLabel)

#Removes .tar from label during creation
shutil.make_archive(proxyArchiveLabel.rsplit('.',1)[0], 'tar', verbose=True)

所以这会在本地目录中创建一个存档。问题是,我想删除我的存档中的一个特定目录,因为它的大小和此任务的必要性不足。

ExecWithLogging('tar -vf %s --delete ./roles/jobs/*' % proxyArchiveLabel)
# ------------
def ExecWithLogging(cmd):
    print cmd
    p = subprocess.Popen(cmd.split(' '), env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
      log.info(p.stdout.readline().strip())
      if(p.poll() is not None):
        break

然而,这似乎基本上没有做任何事情。大小保持不变。如果我在 ExecWithLogging 内部打印 cmd,并且 copy/past 该命令打印到脚本工作目录中的终端,它工作正常。可以肯定的是,我还尝试将完整路径硬编码到创建存档的位置作为 tar -vf %s --delete 命令的一部分,但似乎仍然没有发生任何事情。

我确实在我的 INFO 日志中得到了这个输出:tar: Pattern matching characters used in file names,所以我有点想 Popen 以某种方式错误地解释了我的命令......(或者更确切地说,我更可能错误地传递了一些东西)。

我是不是做错了什么?我还能尝试什么?

您可能需要在 tar 命令中使用 --wildcards 选项,以启用模式匹配。这很可能就是您在日志中看到的内容,只是有点神秘。

编辑: 在回答你的问题为什么?我怀疑 shell 正在执行通配符扩展,而通过 Popen 提供的命令不是。 tar 的 --wildcard 选项强制 tar 执行通配符扩展。
更详细的解释见这里:
Tar and wildcards