如何在Python中等待并在同一行打印输出

6

好的,我正在使用vpython编写一个小型倒计时功能,目前的做法是:

import time
print "5"
time.sleep(1)
print "4"
time.sleep(1)
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print "0"
time.sleep(1)
print "blastoff"

当然,这不是我的代码,但它很好地演示了它。 因此,我想做的是,不打印 5 4 3 2 1 发射 我要 在同一行上打印54321发射。 如何等待一秒钟并在同一行上打印字符。请告诉我,这将是一个很大的帮助。


2
在每个 print 语句后面添加一个逗号。 - rlms
3个回答

3

试试这个:

import time

for i in range(5, 0, -1):
    print i, # print in the same line by adding a "," at the end
    time.sleep(1)
    if i == 1:
        print 'Blastoff!'

这将会按预期工作:

5 4 3 2 1 Blastoff!

编辑

...或者如果你想打印所有内容不带空格(这在问题中没有明确说明):

import time
from __future__ import print_function # not necessary if using Python 3.x

for i in range(5, 0, -1):
    print(i, end="")
    time.sleep(1)
    if i == 1:
        print(' Blastoff!')

以上将打印:
54321 Blastoff!

或者,删除条件测试并将“print 'Blastoff'”行的缩进取消2个位置(8个空格)。 - KevinDTimm
@AswinMurugesh,我不是这样理解问题的,OP想要在同一行打印它们,他明确说明了这一点,这就是全部。在问题中,他第二次只是没有放空格,请重新考虑取消投票。 - Óscar López
@AswinMurugesh “在同一行”下面说,不要断章取义。无论如何,我编辑了我的问题以考虑那种情况。 - Óscar López
再次看到“在同一行上”。但是显然从问题来看,“而不是打印5 4 3 2 1”。因此,这表明他不想要那个。 - Aswin Murugesh
@AswinMurugesh 哎呀,我忘记了定时器。好的,好的,我再次编辑了 :( - Óscar López
显示剩余5条评论

2
在Python 3中,应该向print函数传递end=""

1
以下代码适用于Python 2和Python 3。
但对于Python 3,请参见Ramchandra Apte的好答案。
from sys import stdout
from time import sleep

for i in xrange(5,0,-1):
    stdout.write(str(i))
    sleep(1)
stdout.write(' Blastoff')

"

str(i) 是必需的,以便这段代码在命令行窗口中执行。在编辑 shell 窗口中,可以写成 stdout.write(i),但是 '\b' 信号不会将光标移回,会在其位置上出现一个方块。

"

.

顺便说一下,尝试以下代码以查看发生了什么。 '\b' 触发光标向后移动一个位置,替换前面的字符,因此每个字符都只写在它之前的位置上。这仅适用于命令行窗口,而不是编辑 shell 窗口。
from sys import stdout
from time import sleep

for i in xrange(5,0,-1):
    stdout.write(str(i))
    sleep(1)
    stdout.write('\b')
stdout.write('Blastoff')


raw_input('\n\npause')

复杂化(仍需在命令行窗口中执行):

from sys import stdout
from time import sleep

tu = (' End in 24 seconds',
      ' It remains 20 seconds',
      ' Still only 16 seconds',
      ' Do you realize ? : 12 seconds left !',
      ' !!!! Hey ONLY 8 seconds !!')
for s in tu:
    stdout.write('*')
    sleep(1)
    stdout.write(s)
    sleep(2)
    stdout.write(len(s)*'\b' + len(s)*' ' + len(s)*'\b')
    sleep(1)

stdout.write(len(tu)*'\b' + len(tu)*'!' + ' ')
n = 4
for x in xrange(n,0,-1):
    stdout.write('\b!'+str(x))
    sleep(1)

stdout.write(len(tu)*'\b' + n*'\b' + '\b')
stdout.write('       # !! BLASTOUT !! #\n')
sleep(0.8)
stdout.write('      ## !! BLASTOUT !! ##\n')
sleep(0.8)
stdout.write('     ### !! BLASTOUT !! ##\n')
sleep(0.8)
stdout.write('    #### !! BLASTOUT !! ####\n')
sleep(3)

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