运行 来自 python 的管道 bash 命令

run piped bash commnads from python

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

tail input.txt | grep <pattern>

我写了下面几行

bashCommand = "tail input.txt | grep <pattern>'"
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) print process.communicate()`

您可以在这里找到更详细的解释: https://unix.stackexchange.com/questions/282839/why-wont-this-bash-command-run-when-called-by-python

考虑在 Python 中实现管道,而不是 shell。

from subprocess import Popen, PIPE
p1 = Popen(["tail", "input.txt"], stdout=PIPE)
process = Popen(["grep", "<pattern>"], stdin=p1.stdout)