退格键问题

0 投票
2 回答
1632 浏览
提问于 2025-04-16 07:41

为什么我的这个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 个回答

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 只有在打印出换行符的时候才会刷新。

4

在Python 3中,你需要清空打印缓冲区,这样才能强制把字符写到屏幕上。

在你的脚本开头加上

import sys

并把循环改成

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

撰写回答