与 time.sleep() 在同一行打印 [英] Printing on the same line with time.sleep()
本文介绍了与 time.sleep() 在同一行打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用中间的计时器在同一行上打印两个字符串.代码如下:
I'm trying to print two strings on the same line using a timer in between. Here's the code:
import time
print "hello",
time.sleep(2)
print "world"
但程序似乎等待了两秒钟,然后打印了两个字符串.
But it seems the program waits for two seconds then prints both strings.
推荐答案
在 python 2.7 中,您可以使用 future 包中的 print_function
in python 2.7 you could use the print_function from the future package
from __future__ import print_function
from time import sleep
print("hello, ", end="")
sleep(2)
print("world!")
但是就像你说的,这会等待 2 秒然后打印两个字符串.根据 Gui Rava 的回答,您可以刷新标准输出,这里有一个示例,可以帮助您找到正确的方向:
But like you said, this waits 2 seconds then prints both strings. In light of Gui Rava's answer you can flush stdout, here is a sample which should get you in the right direction:
import time
import sys
def _print(string):
sys.stdout.write(string)
sys.stdout.flush()
_print('hello ')
time.sleep(2)
_print('world')
这篇关于与 time.sleep() 在同一行打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文