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

如何用http.server将函数返回内容逐行输出到网页?

解决http.server遍历内容仅显示一项并生成独立

标签的问题

问题根源

你原代码里的outFunc函数存在逻辑错误:

  • 函数里的for item in out:循环完全无效,因为第一次循环就执行了return out,直接返回整个列表并终止函数,根本没做遍历输出的操作。

两种修改方案

方案1:让outFunc直接生成带

标签的HTML字符串

修改outFunc,遍历列表中的每个元素,为每个元素包裹<p>标签后拼接成完整的HTML片段:

def outFunc():
    tup = getInfo()
    out = list(sum(tup, ()))
    # 用生成器遍历每个元素,生成带<p>的字符串,再拼接成整体
    return ''.join(f"<p>{item}</p>" for item in out)

然后在do_GET中直接写入这个HTML片段:

def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("<html><head><title>Most Recent Domains</title></head>", "utf-8"))
    self.wfile.write(bytes("<body>", "utf-8"))
    # 直接写入生成好的带<p>标签的内容
    self.wfile.write(bytes(outFunc(), "utf-8"))
    self.wfile.write(bytes("</body></html>", "utf-8"))

方案2:在do_GET中遍历列表逐个输出

标签

保持outFunc仅返回原始列表(去掉无用的for循环):

def outFunc():
    tup = getInfo()
    out = list(sum(tup, ()))
    return out  # 直接返回处理后的列表

然后在do_GET方法里遍历列表,逐个写入带<p>标签的元素:

def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("<html><head><title>Most Recent Domains</title></head>", "utf-8"))
    self.wfile.write(bytes("<body>", "utf-8"))
    # 遍历outFunc返回的列表,逐个生成<p>标签并写入
    for item in outFunc():
        self.wfile.write(bytes(f"<p>{item}</p>", "utf-8"))
    self.wfile.write(bytes("</body></html>", "utf-8"))

内容的提问来源于stack exchange,提问作者Z.Davey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:52:35