退格麻烦

时间:2010-11-27 18:06:48

标签: python python-3.x console-application

为什么我的Python时钟只从Python2运行,Python3什么都不做。

from __future__ import print_function
import time
wipe = '\b'*len(time.asctime())
print("The current date and time are: "+' '*len(wipe), end='')
while True:
    print(wipe+time.asctime(), end='')
    time.sleep(1)

2 个答案:

答案 0 :(得分:4)

在Python 3中,您需要刷新打印缓冲区以强制将字符写入屏幕。

添加

import sys

到脚本的开头并将循环更改为

while True:
    print(wipe+time.asctime(), end='')
    sys.stdout.flush()
    time.sleep(1)

答案 1 :(得分:1)

问题不在于python版本,而在于您忘记刷新标准输出。尝试将代码更改为:

from __future__ import print_function
import time
import sys
wipe = '\b'*len(time.asctime())
print("The current date and time are: "+' '*len(wipe), end='')
while True:
    print(wipe+time.asctime(), end='')
    sys.stdout.flush()
    time.sleep(1)

sys.stdout仅在打印换行符时刷新。