相当于find-exec的Python



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

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

但每次我得到:"find:缺少stderr中"-exec"的参数。

与之相当的python是什么?

我天真的想法是:

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

肯定有更好、更像蟒蛇的方法吗?

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

但是对于Popen,如果可以避免的话,你通常不想使用shell

import subprocess
subprocess.Popen(('find', '/tmp/mount', '-type', 'f',
                  '-name', '*.rpmsave', '-exec', 'rm', '-f', '{}', ';'))

基本上就是这样做的。您需要协调三件不同的事情: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))

如果你发现自己经常做这些事情。这可能是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')]

最新更新