从python运行管道bash命令

从python运行管道bash命令,python,bash,subprocess,Python,Bash,Subprocess,我想在python脚本中运行以下bash命令 tail input.txt | grep <pattern> tail input.txt | grep 我写了以下几行 bashCommand = "tail input.txt | grep <pattern>'" process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) bashCommand=“tail i

我想在python脚本中运行以下bash命令

tail input.txt | grep <pattern>
tail input.txt | grep
我写了以下几行

bashCommand = "tail input.txt | grep <pattern>'"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
bashCommand=“tail input.txt | grep”
process=subprocess.Popen(bashCommand.split(),stdout=subprocess.PIPE)

但这最终只是打印出输入文件的尾部,而不是我试图grep的模式。如何避免这种情况?

您可以将
shell=True
传递给
subprocess.Popen
。这将通过shell运行命令。如果执行此操作,则需要传递字符串而不是列表:

process=subprocess.Popen(“tail input.txt | grep”,stdout=subprocess.PIPE,shell=True) 打印进程。通信()`

您可以在此处找到更详细的说明:

您可以将
shell=True
传递给
子流程.Popen
。这将通过shell运行命令。如果执行此操作,则需要传递字符串而不是列表:

process=subprocess.Popen(“tail input.txt | grep”,stdout=subprocess.PIPE,shell=True) 打印进程。通信()`

您可以在此处找到更详细的说明:
考虑用Python实现管道,而不是shell

from subprocess import Popen, PIPE
p1 = Popen(["tail", "input.txt"], stdout=PIPE)
process = Popen(["grep", "<pattern>"], stdin=p1.stdout)
从子流程导入Popen,管道
p1=Popen([“tail”,“input.txt”],stdout=PIPE)
process=Popen([“grep”,“”],stdin=p1.stdout)

考虑用Python实现管道,而不是shell

from subprocess import Popen, PIPE
p1 = Popen(["tail", "input.txt"], stdout=PIPE)
process = Popen(["grep", "<pattern>"], stdin=p1.stdout)
从子流程导入Popen,管道
p1=Popen([“tail”,“input.txt”],stdout=PIPE)
process=Popen([“grep”,“”],stdin=p1.stdout)

谢谢Robbe!有没有办法让它与变量一起工作?哪里可以用变量替换?是的,您可以始终使用字符串格式。或者你可以使用切普纳提出的解决方案。他的解决方案更可靠。谢谢Robbe!有没有办法让它与变量一起工作?哪里可以用变量替换?是的,您可以始终使用字符串格式。或者你可以使用切普纳提出的解决方案。他的解决方案更加稳健。