Python, subprocess, how to pass multiples variables

夙愿已清 提交于 2021-02-05 07:14:05

问题


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 grepcommands. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!