【问题标题】:python stdout to file does not respond in real timepython stdout到文件没有实时响应
【发布时间】:2015-03-21 00:54:07
【问题描述】:

写一个简单的python脚本test.py:

  import time
  print "begin"
  time.sleep(10)
  print "stop"

在 bash 中,运行

python test.py > log.txt

我观察到“开始”和“停止”在 10 秒后同时出现在 log.txt 中。

这是预期的行为吗?

【问题讨论】:

    标签: python bash redirect io pipe


    【解决方案1】:

    您是否尝试过使用 -u 选项调用 python,“强制标准输入、标准输出和标准错误完全无缓冲”=>

    python -u test.py > log.txt
    

    【讨论】:

      【解决方案2】:

      您需要在打印后刷新缓冲区。

      import sys
      import time
      
      print "begin"
      sys.stdout.flush()
      
      time.sleep(10)
      
      print "end"
      sys.stdout.flush()
      

      或者在 Python 3 中:

      # This can also be done in Python 2.6+ with
      # from __future__ import print_function
      
      import time
      
      print("begin", flush=True)
      time.sleep(10)
      print("end", flush=True)
      

      【讨论】:

        【解决方案3】:

        这是因为实际写入仅在缓冲区已满或文件关闭时发生。当程序结束时(10s 后),缓冲区被清空,数据被写入,文件被关闭。

        【讨论】:

          猜你喜欢
          • 2022-10-13
          • 1970-01-01
          • 2021-06-16
          • 2014-04-27
          • 2015-02-14
          • 2021-12-19
          • 2016-10-22
          • 2011-10-06
          相关资源
          最近更新 更多