【问题标题】:run piped bash commnads from python从 python 运行管道 bash 命令
【发布时间】:2020-11-10 17:41:43
【问题描述】:

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

tail input.txt | grep <pattern>

我写了以下几行

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

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

【问题讨论】:

    标签: python bash subprocess


    【解决方案1】:

    您可以将shell=True 传递给subprocess.Popen。这将通过 shell 运行命令。如果你这样做,你需要传递一个字符串而不是一个列表:

    process = subprocess.Popen("tail input.txt | grep ", stdout=subprocess.PIPE, shell=True) 打印 process.communicate()`

    您可以在此处找到更详细的说明: https://unix.stackexchange.com/questions/282839/why-wont-this-bash-command-run-when-called-by-python

    【讨论】:

    • 谢谢罗贝!有没有办法让它与变量一起工作? 在哪里可以用 var 代替?
    • 是的,您始终可以使用字符串格式。或者您可以使用 chepner 提出的解决方案。他的解决方案更强大。
    【解决方案2】:

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

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

    【讨论】:

      最近更新 更多