Python:打印到一行,打印之间有时间延迟 [英] Python: Print to one line with time delay between prints

查看:284
本文介绍了Python:打印到一行,打印之间有时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作(为了好玩)python打印出'LOADING ...'到控制台。扭曲的是,我想打印出来,他们之间的睡眠时间为0.1秒(ish)。到目前为止,我做到了这一点:

 从时间导入睡眠
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')

  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 with sleep(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆