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

如何在文件的同一行中打印下载进度百分比?

嗨,这个问题我遇见过!核心原因是当你把sys.stdout重定向到文件时,文件流默认是块缓冲模式(和终端的行缓冲不一样),再加上print函数的一些隐式处理,就导致了意外换行。给你几个可行的解决方案:

方法一:给print加上flush=True参数

print函数默认会把输出暂存在缓冲区,直到满足条件才写入文件,这时候可能会带出额外的换行。加上flush=True可以强制立即刷新缓冲区,确保内容按你期望的方式写入:

with open(LOG_FILE, 'w') as sys.stdout:
    print("\r Downloaded {} of {} bytes {:.2f}%".format(bytes_so_far, total_size, percent), end='', flush=True)
    if bytes_so_far >= total_size:
        print('\n', flush=True)

方法二:继续用sys.stdout.write(你已经验证过的可靠方式)

相比print,sys.stdout.write更直接,不会有额外的隐式处理,配合flush就能稳定输出:

with open(LOG_FILE, 'w') as sys.stdout:
    sys.stdout.write("\r Downloaded {} of {} bytes {:.2f}%".format(bytes_so_far, total_size, percent))
    sys.stdout.flush()
    if bytes_so_far >= total_size:
        sys.stdout.write('\n')
        sys.stdout.flush()

额外提示(针对Windows系统)

如果是在Windows上,建议打开文件时加上newline=''参数,避免文本模式自动把\n转换成\r\n,导致换行符混乱:

with open(LOG_FILE, 'w', newline='') as sys.stdout:
    print("\r Downloaded {} of {} bytes {:.2f}%".format(bytes_so_far, total_size, percent), end='', flush=True)
    if bytes_so_far >= total_size:
        print('\n', flush=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:31:13