子流程中的变量

Variable in subprocess

有没有办法在子进程中传递变量?这没有用。

subprocess.check_output(["cat test.txt | grep %s"], shell=True) %(variable)

您可以使用 str.format:

"cat test.txt | grep {}".format(variable)

或者使用旧样式格式将变量直接放在后面。

"cat test.txt | grep %s"%variable

使用 shell=True:

时,您的列表也是多余的
subprocess.check_output("cat fable.txt | grep %s" %variable, shell=True)

如果您使用的参数列表没有 shell = True,您可以使用 Popen:

from subprocess import Popen,PIPE
p1 = Popen(["cat","text.txt"], stdout=PIPE)
p2 = Popen(["grep", variable], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  
out,err = p2.communicate()
p1.wait()
print(out)