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

Python多行字符串len()计数错误致CGI响应内容被截断

Apache CGI Python程序响应体截断问题的解决思路

问题根源

  • Python的print()函数在Windows环境下会自动将字符串中的\n转换为系统默认的行结束符\r\n,导致实际发送的内容长度比len(html)计算的原始字符串长度大
  • 手动用.replace('\n','\r\n')替换后,print()会再次转换\n,最终生成\r\r\n多余字符,且Content-Length的计算没有匹配实际发送的内容长度,依然导致截断

可行解决方案

方案1:禁用print的自动换行转换

直接使用sys.stdout.write()替代print(),避免自动转换换行符,确保计算的长度和实际发送内容一致:

#!C:/Python311/python.exe
import sys

html = """<!doctype html />
<html>
<head>
</head>
<body>
    <h1>Hello CGI World</h1>
</body>
</html>"""

# 直接写入所有内容,不触发换行符自动转换
sys.stdout.write("Content-Type: text/html\n")
sys.stdout.write(f"Content-Length: {len(html)}\n")
sys.stdout.write("\n")
sys.stdout.write(html)

方案2:计算转换后的实际内容长度

如果要保留print(),需先计算转换后的完整响应长度,再统一处理换行符:

#!C:/Python311/python.exe
import sys

html = """<!doctype html />
<html>
<head>
</head>
<body>
    <h1>Hello CGI World</h1>
</body>
</html>"""

# 拼接响应头和响应体,计算转换后的长度
html_converted = html.replace('\n', '\r\n')
content_length = len(html_converted)

# 拼接完整响应并转换换行符
response = "\r\n".join([
    "Content-Type: text/html",
    f"Content-Length: {content_length}",
    "",
    html_converted
])

sys.stdout.write(response)

方案3:省略Content-Length(推荐)

Apache CGI环境会自动处理响应体长度,无需手动设置,彻底规避长度计算问题:

#!C:/Python311/python.exe

html = """<!doctype html />
<html>
<head>
</head>
<body>
    <h1>Hello CGI World</h1>
</body>
</html>"""
print("Content-Type: text/html")
print()  # 空行分隔头和体
print(html)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:55:29