You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows系统中使用 覆盖进度条失效问题求助

解决Windows下Python进度条无法覆盖的问题

问题原因

Windows控制台对回车符\r的处理和类Unix系统存在差异:类Unix系统中\r会将光标移至行首,后续输出会直接覆盖原有内容;但Windows仅移动光标位置,不会自动清除行内已有的内容,如果新输出的字符串长度短于之前的内容,旧内容的后半部分会残留显示,导致进度条无法正常覆盖更新。

解决方案1:填充空格覆盖旧内容

这种方法无需额外依赖,兼容性强,通过将每次输出的进度条字符串填充至终端宽度,确保完全覆盖之前的行内容:

import time
import sys
import os

def loading_bar(count, total, suffix=''):
    length = 60
    endlength = int(round(length * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * endlength + '-' * (length - endlength)
    # 构造进度条基础字符串
    bar_str = f'[{bar}] {percents}% ...{suffix}'
    # 获取终端宽度,异常时使用 fallback 值
    try:
        terminal_width = os.get_terminal_size().columns
    except:
        terminal_width = 100
    # 用空格填充至终端宽度,确保覆盖整行旧内容
    bar_str = bar_str.ljust(terminal_width)
    sys.stdout.write(f'\r{bar_str}')
    sys.stdout.flush()
    
def loading():
    items = list(range(0, 200))
    total_items = len(items)
    print("Loading:")
    for i, item in enumerate(items):
        time.sleep(0.1)
        loading_bar(i + 1, total_items, suffix=str(item))
    print()
    print("Done!")
    time.sleep(1)

loading()

解决方案2:使用ANSI转义码清除行内容

这种方法视觉效果更干净,通过ANSI转义码\033[K清除光标到行尾的内容,但Windows默认不支持ANSI转义,需要先启用控制台的VT100模式:

import time
import sys
import os

# Windows下启用控制台VT100模式以支持ANSI转义码
if os.name == 'nt':
    import ctypes
    kernel32 = ctypes.windll.kernel32
    kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

def loading_bar(count, total, suffix=''):
    length = 60
    endlength = int(round(length * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * endlength + '-' * (length - endlength)
    # \033[K 清除光标到行尾的内容,再输出进度条
    sys.stdout.write(f'\r\033[K[{bar}] {percents}% ...{suffix}')
    sys.stdout.flush()
    
def loading():
    items = list(range(0, 200))
    total_items = len(items)
    print("Loading:")
    for i, item in enumerate(items):
        time.sleep(0.1)
        loading_bar(i + 1, total_items, suffix=str(item))
    print()
    print("Done!")
    time.sleep(1)

loading()

内容的提问来源于stack exchange,提问作者TH3KINGOFHYRULE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:43:27