【问题标题】:Grep python output stream (tried print and stdout)Grep python 输出流(尝试打印和标准输出)
【发布时间】:2019-02-06 13:20:05
【问题描述】:

这个答案说它很简单:

pipe python logging stdout stream output to grep

python main.py 2>&1 | grep INFO

我有以下文件,我已尝试使用 print()sys.stdout.write()

import sys
from time import sleep

while True:
    sleep(1)
    sys.stdout.write("this is a thing")
    # Also tried print()

我正在尝试通过以下方式收集"thing"

python output.py 2>&1 | grep "thing"

【问题讨论】:

    标签: python grep stdout


    【解决方案1】:

    你需要使用newline,最好使用flushstdout

    import sys
    from time import sleep
    
    while True:
        sys.stdout.write("this is a thing\n")
        sys.stdout.flush()
        sleep(1)
    

    【讨论】:

      【解决方案2】:
      while True:
          sleep(1)
          print("this is a thing", flush=True)
      

      也可以,无需直接使用标准输出。

      默认情况下,print 使用缓冲区进行输出,只需在每次调用时刷新它,您就可以获得半实时流。

      【讨论】:

        【解决方案3】:

        作为补充:如果输出会发送到 stderr,这里的情况并非如此,您仍然会在终端中看到它,因为管道 |如果您未另行指定,则仅重定向标准输出 其余的未过滤到终端

        【讨论】:

          猜你喜欢
          • 2013-05-01
          • 2016-01-31
          • 1970-01-01
          • 2016-03-04
          • 2021-02-06
          • 1970-01-01
          • 2012-04-14
          • 1970-01-01
          • 2018-11-25
          相关资源
          最近更新 更多