Trim 运行 程序的输出

Trim output of running program

我有一个程序,当它运行时,会输出数百行以“Info:”开头的行和一些有用的输出行。为了让事情变得更简单,我创建了一个简单的 python 和 bash 组合脚本来模拟我遇到的问题:

wait_2sec.py:

import time

print("Hello!")
time.sleep(2)
print("Goodbye!")

我正在尝试 trim 我的输出 运行:

 python wait_2sec.py | sed '/Goodbye/d'

然而,sed 不输出你好!直到 python 脚本完成。我不知道管道是否等到程序完成后才开始 运行 sed 命令,或者 sed 命令是否挂断。 如果 sed 不适用于此用例,我愿意使用另一个命令 trim 输出。

您可以使用以下命令尝试 运行 您的脚本:

unbuffer python wait_2sec.py | sed '/Goodbye/d'

参考:https://unix.stackexchange.com/a/200413

I don't know whether the pipe waits until after the program is finished to begin running the sed command, or if the sed command is the hangup.

实际上两者都不是,它是 python 通常缓冲其输出(如果不是到终端)直到缓冲区已满,因此如果安装了 unbuffer,Moustapha 的建议可能会起作用。但是您可以简单地使用 python 的内置选项 -u强制 stdout 和 stderr 流无缓冲。)代替:

python -u wait_2sec.py | sed '/Goodbye/d'