find command with exec in python subprocess gives

2019-07-20 12:45发布

问题:

I'm trying to execute the following command using subprocess module (python)

/usr/bin/find <filepath> -maxdepth 1 -type f -iname "<pattern>" -exec basename {} \;

But, it gives the following error :

/usr/bin/find: missing argument to `-exec'

I am guessing it's to do with escaping some characters. But not getting how to get over this.

Any help is appreciated. Thanks.

回答1:

An answer on another question helped: https://stackoverflow.com/a/15035344/971529

import subprocess

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

The thing I couldn't figure out was that the semi-colon didn't need to be escaped, since normally the semi-colon is interpreted by bash, and needs to be escaped.

In bash this equivelent is:

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


回答2:

One more hint: Using the syntax r'bla' allows using backslashs without having to quote them:

r'... -exec basename {} \;'

Provides better readability.



回答3:

remember escaping " is required and also escaping \ used before ; is also required

your command might look something like:

p1 = subprocess.Popen(["/usr/bin/find", "<filepath> -maxdepth 1 -type f -iname \"<pattern>\" -exec basename {} \\;"])
p1.communicate()