Search code examples
pythonpopen3

Python equivalent to find -exec


I'm trying to run this BASH command in Popen:

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

But every time I get: "find: missing argument to `-exec'\n" in stderr.

What would the python equivalent of this be?

My naive aproach would be:

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

surely there is a better, more pythonic way of doing this?


Solution

  • You've actually got two questions here — first, why your Popen construction doesn't work, and second, how to use os.walk properly. Ned answered the second one, so I'll address the first one: you need to be aware of shell escaping. The \; is an escaped ; since normally ; would be interpreted by Bash as separating two shell commands, and would not be passed to find. (In some other shells, {} must also be escaped.)

    But with Popen you don't generally want to use a shell if you can avoid it. So, this should work:

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