Python,子进程,如何传递多个变量 [英] Python, subprocess, how to pass multiples variables

查看:33
本文介绍了Python,子进程,如何传递多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 subprocess 模块来运行 find &grep 命令有两个不同的变量.我有一个语法错误,但我只是没有看到.

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) 

两个变量:

 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) 

有人可以帮忙吗?

谢谢.

推荐答案

yakxxx 是对的,但是 shell=True 不是最优的.

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

最好做

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.

例如,想象 'My 9" collection' 等的 pathpath_f 值.这将混淆 shellfindgrep 命令.有很多方法可以解决,但它们比上面的要难.

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.

请参阅此处.

这篇关于Python,子进程,如何传递多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆