6

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.

avasal
  • 14,350
  • 4
  • 31
  • 47
shruthi
  • 327
  • 3
  • 5
  • 13

3 Answers3

15

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 {} \;
Community
  • 1
  • 1
isaaclw
  • 923
  • 9
  • 22
0

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

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

Provides better readability.

Alfe
  • 56,346
  • 20
  • 107
  • 159
-2

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()
avasal
  • 14,350
  • 4
  • 31
  • 47