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

使用tqdm迭代URL时,如何实现单行替换打印而非新增换行?

解决tqdm迭代时同一行显示当前URL的问题

直接修改你的代码,核心是利用回车符回到行首并强制刷新输出,同时处理URL的无效换行符:

import urllib
from tqdm.auto import tqdm
import time
import sys

# 一次性读取所有行并处理换行,避免重复打开文件
with open(r"millard.txt", 'r') as fp:
    lines = fp.read().splitlines()
total_lines = len(lines)
print('Total Number of lines:', total_lines)

working = []
danky = "Progress"

for line in tqdm(lines, total=total_lines, position=0, leave=False, desc=danky):
    new_link = f"http://www.{line.strip()}"  # 去除行尾空白和换行符
    # 用\r回到行首,加空格覆盖旧内容,end=''避免自动换行
    print(f"\rGetting {new_link} " + " " * 30, end='')
    sys.stdout.flush()  # 强制刷新输出,确保内容即时显示
    try:
        urllib.request.urlopen(new_link, timeout=5)  # 加超时防止程序卡住
        working.append(new_link)
    except (urllib.error.HTTPError, urllib.error.URLError):
        pass  # 无需额外操作,跳过不可用链接即可
    time.sleep(0.01)

with open(r'final.txt', 'w') as fp:
    for item in working:
        fp.write(f"{item}\n")  # 每个有效URL单独占一行
print('\nDone')

关键修改说明:

  • \r回车符:每次打印前回到当前行开头,新内容直接覆盖旧内容,不会新增换行。
  • 空格填充:" " * 30用来覆盖上一次可能更长的URL内容,防止残留字符。
  • sys.stdout.flush():强制刷新输出缓存,确保修改后的内容立刻显示在终端。
  • strip()处理:去除行尾的换行符和空白,避免生成带无效换行的URL。
  • 超时参数:给urlopen添加timeout=5,避免单个无响应URL卡住整个程序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:40:22