【问题标题】:Why isn't sys.stdout.flush() printing all the characters on the same line?为什么 sys.stdout.flush() 不在同一行打印所有字符?
【发布时间】:2021-11-27 09:57:18
【问题描述】:

这是我的代码:

wait = "..."
for char in wait:
   sys.stdout.flush()
   time.sleep(1)
   print(char)

我正在尝试将其输出:

...

但它却输出:

.
.
.

我不明白为什么 sys.stdout.flush 没有效果。

【问题讨论】:

    标签: python python-3.x time flush sys


    【解决方案1】:

    如果你在 Python 解释器中输入help(print),你会得到:

    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    

    使用这些信息:

    for char in wait:
       time.sleep(1)
       print(char, end='', flush=True)
    

    【讨论】:

      【解决方案2】:

      std.out.flush() 只是将缓冲区中的内容写入屏幕

      默认情况下,print() 在末尾添加 \n 以写入新行。你可以通过print(s, end='')关闭它

      【讨论】:

        【解决方案3】:

        print中使用参数end=''可以达到预期的效果:
        试试这个:

        import sys
        import time
        wait = "..."
        for char in wait:
           sys.stdout.flush()
           time.sleep(1)
           print(char, end='')
        

        您可以阅读有关end 参数here 的更多信息

        【讨论】:

          【解决方案4】:

          试试看:

          import sys
          import time
          
          wait = "..."
          for char in wait:
              time.sleep(1)
              print(char, end="", file=sys.stdout, flush=True)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-13
            • 2012-09-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多