2

I am using the subprocess module to run a find & grep command with two different variables. I have a syntax error but I just don't see it.

With one variable, it runs just fine:

path = "src"
path_f = "TC" 
subprocess.Popen('find /dir1/tag/common/dir2/dir3 /dir1/tag/common/dir2/dir3/dir4/ -iname "%s"'%path, shell=True) 

Two variables:

 subprocess.Popen('find /dir1/tag/common/dir2/dir3 /dir1/tag/common/dir2/dir3/dir4/ -iname "%s"* | grep "%s"  > fileList.txt'%path, %path_f, shell=True) 

Can someone help ?

Thanks.

hlx
  • 182
  • 1
  • 4
  • 15

2 Answers2

4

It should be:

subprocess.Popen('find /dir1/tag/common/dir2/dir3 /dir1/tag/common/dir2/dir3/dir4/ -iname "%s"* | grep "%s"  > fileList.txt'% (path, path_f), shell=True) 

Notice brackets added around (path, path_f) and percent removed

yakxxx
  • 2,841
  • 2
  • 21
  • 22
  • 1
    Note that it could be more readable to do a `... -iname "%(name)s"* | grep "%(pattern)s" ..." % dict(name=path, pattern=path_f)`, that is, to name the different placeholders.. – Pierre GM Oct 05 '12 at 09:32
0

yakxxx is right, but shell=True is not optimal.

Better do

sp1 = subprocess.Popen(['find', '/dir1/tag/common/dir2/dir3', '/dir1/tag/common/dir2/dir3', '/dir4/', '-iname', path], stdout=subprocess.PIPE)
sp2 = subprocess.Popen(['grep', path_f], stdin=sp1.stdout, stdout=open('fileList.txt', 'w'))
sp1.stdout.close() # for SIGPIPE from sp2 to sp1

as it gives you better control over what happens, expecially no shell escaping crosses your way.

For example, imagine a path or path_f value of 'My 9" collection' etc. This will confuse the shell at both the find and the grepcommands. There are ways around it, but they are harder than the above.

See here.

Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217