在 Python 3.6 和 Windows 下的 3.7 中使用 end="" 的不可预测的打印函数行为

Unpredictable print function behavior with end="" in Python 3.6 and 3.7 under Windows

下面的代码工作起来很奇怪

import time

def test_print_end(EOL):
    for i in range(3):
        print("Processing... ", end=EOL)
        # You may replace ``time.sleep(5)`` with the long-time processing.
        time.sleep(5)
        print("Done")    

print('EOL == ""')
test_print_end(EOL = "")
print('EOL == "\n"')
test_print_end(EOL = "\n")
  1. EOL == "":

    1. 虽然 运行 Spyder 控制台中的代码可以预测:打印 "Processing... ",然后等待 5 秒并在同一行打印 " Done"
    2. 但在 "cmd.exe" 它等待 3 秒,然后同时打印 "Processing... Done"
  2. EOL == "\n" 它在 Spyder 控制台和 cmd.exe 中的工作方式相同:打印 "Processing... ",然后等待 5 秒并在新行中打印 " Done"

它是功能还是错误?

我的环境是:

  1. ('64位', 'WindowsPE')
  2. Windows-7-6.1.7601-SP1
  3. Python 3.7.2(默认,2019 年 2 月 11 日,14:11:50)[MSC v.1915 64 位 (AMD64)]
  4. Python 3.6.6(默认,2018 年 6 月 28 日,11:21:07)[MSC v.1900 32 位(英特尔)]

似乎 Python 正在等待当前行完成后再打印。此行为可能因不同版本或环境而异。在您的情况下,您可以添加 flush parameter 以强制打印部分行。

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

print("Processing... ", end=EOL, flush=True)