【发布时间】: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
这是我的代码:
wait = "..."
for char in wait:
sys.stdout.flush()
time.sleep(1)
print(char)
我正在尝试将其输出:
...
但它却输出:
.
.
.
我不明白为什么 sys.stdout.flush 没有效果。
【问题讨论】:
标签: python python-3.x time flush sys
如果你在 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)
【讨论】:
std.out.flush() 只是将缓冲区中的内容写入屏幕
默认情况下,print() 在末尾添加 \n 以写入新行。你可以通过print(s, end='')关闭它
【讨论】:
在print中使用参数end=''可以达到预期的效果:
试试这个:
import sys
import time
wait = "..."
for char in wait:
sys.stdout.flush()
time.sleep(1)
print(char, end='')
您可以阅读有关end 参数here 的更多信息
【讨论】:
试试看:
import sys
import time
wait = "..."
for char in wait:
time.sleep(1)
print(char, end="", file=sys.stdout, flush=True)
【讨论】: