问题
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.
回答1:
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 grep
commands. There are ways around it, but they are harder than the above.
See here.
回答2:
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
来源:https://stackoverflow.com/questions/12743286/python-subprocess-how-to-pass-multiples-variables