Python:打印到一行,打印之间有时间延迟 [英] Python: Print to one line with time delay between prints
问题描述
从时间导入睡眠
print('L');睡觉(0.1)
print('O');睡觉(0.1)
print('A');睡觉(0.1)
等等...
然而,它将每行打印成不同的行。
另外我不能输入 print('LOADING ...')
,因为它会瞬间打印,而不是字母在 sleep(0.1)
之间。
这个例子很简单,但是引发了一个更为普遍的问题:是否有可能打印多个字符串与其他函数正在执行的字符串打印之间的一行?
在Python2中,如果你在字符串后面加一个逗号,打印不会新增一行。然而,输出可能会被缓冲,所以看到打印字符缓慢,你可能还需要刷新标准输出:
从时间import sleep
$因此,要慢慢地打印一些文本,你可以像这样使用
import sys
print'L',
sys.stdout.flush()
sleep(0.1)
for-loop
:pre
from time import sleep
import sys
def print_slowly(text):
for c in text:
print c,
sys.stdout.flush()
sleep(0.5)
print_slowly('LOA')
$ c在Python3中,更改
print $ c $>
$ c,
到
print(c,end ='')
I want to make (for fun) python print out 'LOADING...' to console. The twist is that I want to print it out letter by letter with sleep time between them of 0.1 seconds (ish). So far I did this:
from time import sleep print('L') ; sleep(0.1) print('O') ; sleep(0.1) print('A') ; sleep(0.1) etc...
However that prints it to separate lines each.
Also I cant just type
print('LOADING...')
since it will print instantaneously, not letter by letter withsleep(0.1)
in between.The example is trivial but it raises a more general question: Is it possible to print multiple strings to one line with other function being executed in between the string prints?
解决方案In Python2, if you put a comma after the string, print does not add a new line. However, the output may be buffered, so to see the character printed slowly, you may also need to flush stdout:
from time import sleep import sys print 'L', sys.stdout.flush() sleep(0.1)
So to print some text slowly, you could use a
for-loop
like this:from time import sleep import sys def print_slowly(text): for c in text: print c, sys.stdout.flush() sleep(0.5) print_slowly('LOA')
In Python3, change
print c,
to
print(c, end='')
这篇关于Python:打印到一行,打印之间有时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!