3

我正在尝试在 Popen 中运行此 BASH 命令:

find /tmp/mount -type f -name "*.rpmsave" -exec rm -f {} \;

但是每次我在标准错误中得到:“find: missing argument to `-exec'\n”。

与此等效的 python 是什么?

我天真的方法是:

for (root,files,subdirs) in os.walk('/tmp/mount'):
    for file in files:
        if '.rpmsave' in file:
            os.remove(file)

肯定有更好,更蟒蛇的方式来做到这一点?

4

3 回答 3

4

你实际上有两个问题——第一,为什么你的Popen构造不起作用,第二,如何os.walk正确使用。Ned 回答了第二个问题,所以我将解决第一个问题:您需要注意 shell 转义。\;是转义的,;因为通常;Bash 会将其解释为分隔两个 shell 命令,并且不会传递给find. (在其他一些 shell 中,{}也必须进行转义。)

但是,Popen如果可以避免的话,您通常不想使用外壳。所以,这应该工作:

import subprocess

subprocess.Popen(('find', '/tmp/mount', '-type', 'f',
                  '-name', '*.rpmsave', '-exec', 'rm', '-f', '{}', ';'))
于 2013-02-23T00:07:12.627 回答
2

你所拥有的基本上就是这样做的方法。您正在协调三件不同的事情:1) 遍历树,2) 仅对 .rpmsave 文件进行操作,以及 3) 删除这些文件。您会在哪里找到可以在本地完成所有这些操作而无需拼写出来的东西?Bash 命令和 Python 代码都具有大致相同的复杂性,这并不奇怪。

但是您必须修复代码,如下所示:

for root,files,subdirs in os.walk('/tmp/mount'):
    for file in files:
        if file.endswith('.rpmsave'):
            os.remove(os.path.join(root, file))
于 2013-02-22T23:59:44.687 回答
1

如果你发现自己经常做这些事情。这可能是 os.walk 的有用包装器:

def files(dir):
   # note you have subdirs and files flipped in your code
   for root,subdirs,files in os.walk(dir):
      for file in files:
         yield os.path.join(root,file)

要删除目录中具有特定扩展名的一堆文件:

[os.remove(file) for file in files(directory) if file.endswith('.extension')]
于 2013-02-23T00:13:54.803 回答