与time.sleep()同时在同一行打印输出

3

我想在同一行上使用计时器打印两个字符串。以下是代码:

import time

print "hello",
time.sleep(2)
print "world"

但是看起来程序会等待两秒钟,然后打印两个字符串。

可能是[无换行打印(print 'a',)会打印一个空格,如何移除?]的重复问题。(https://dev59.com/q2855IYBdhLWcg3wKw9Y) - Andy
2
对我来说这样可以,只需在两个单词之间等待。你可以尝试在其中刷新stdout(import sys; sys.stdout.flush())。 - jonrsharpe
2个回答

10
问题在于,默认情况下,控制台输出是被缓存的。 自Python 3.3以来,print()支持关键字参数flush参见文档):
print('hello', flush=True)

如果您使用的是早期版本的 Python,则可以按照以下方式强制刷新:

import sys
sys.stdout.flush()

5

在Python 2.7中,您可以使用来自future包的print_function。

from __future__ import print_function
from time import sleep

print("hello, ", end="")
sleep(2)
print("world!")

但正如您所说,它将等待2秒钟然后打印两个字符串。根据Gui Rava的回答,您可以刷新标准输出,这里是一个示例,应该可以帮助您朝着正确的方向前进:

import time
import sys

def _print(string):
    sys.stdout.write(string)
    sys.stdout.flush()

_print('hello ')
time.sleep(2)
_print('world')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接