Python控制台自动更新时分秒多行打印问题排查
问题原因
原代码的核心问题是光标位置控制错误:
- 每次循环执行第二句print时都会新增一个换行符,光标会停在最新的秒数所在行,下一轮循环的
\r只能刷新当前光标所在行,无法回到上一行的小时分钟所在行,因此第一行内容永远不会更新 - 未做内容长度对齐,可能出现旧内容残留的问题
修复方案
使用ANSI转义序列控制光标位置,每次刷新前将光标移到两行的起始位置,依次更新两行内容即可:
import time from datetime import datetime # 预先打印两行占位,保证初始光标位置正确 print("Clock: 00:00 AM") print("Seconds: 00") while True: now = datetime.now() current_time = now.strftime("%I:%M %p") current_second = now.strftime("%S") # ANSI转义序列:将光标上移2行,回到第一行开头 print("\033[2F", end='') # 刷新第一行时钟,固定输出长度避免残留 print(f"Clock: {current_time}", end=' \n') # 刷新第二行秒数 print(f"Seconds: {current_second}", end=' ') time.sleep(1)
如果运行环境是Windows旧版CMD,不支持ANSI转义序列,可以用清屏方案兼容,缺点是会有轻微闪烁:
import time import os from datetime import datetime while True: # 适配不同系统的清屏命令 os.system('cls' if os.name == 'nt' else 'clear') now = datetime.now() current_time = now.strftime("%I:%M %p") current_second = now.strftime("%S") print(f"Clock: {current_time}") print(f"Seconds: {current_second}") time.sleep(1)
内容的提问来源于stack exchange,提问作者Tasman Orkiszewski
相关产品推荐
相关产品推荐

