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

如何让Python subprocess获取Poetry show的完整非截断输出?

解决Poetry Show输出被截断的问题

以下几种方法可以帮你获取poetry show的完整输出:

  • 改用subprocess.run()结合capture_output=True读取输出,该方法会等待进程完全结束后再读取所有内容,避免缓冲截断:
import subprocess

def get_full_poetry_output():
    try:
        result = subprocess.run(
            ["poetry", "show"],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"执行出错: {e.stderr}")
        return ""

# 将完整输出写入文件
full_content = get_full_poetry_output()
with open("poetry_deps_full.txt", "w", encoding="utf-8") as f:
    f.write(full_content)
  • 强制关闭输出缓冲,通过设置PYTHONUNBUFFERED环境变量,让Poetry的输出实时刷新:
import subprocess
import os

env = os.environ.copy()
env["PYTHONUNBUFFERED"] = "1"

try:
    result = subprocess.run(
        ["poetry", "show"],
        capture_output=True,
        text=True,
        env=env,
        check=True
    )
    with open("poetry_deps_full.txt", "w", encoding="utf-8") as f:
        f.write(result.stdout)
except subprocess.CalledProcessError as e:
    print(f"执行出错: {e.stderr}")
  • 直接调用Poetry的Python API获取依赖信息,这是最可靠的方式,还能自定义输出格式:
from poetry.factory import Factory

# 加载当前项目的Poetry配置
poetry = Factory().create_poetry(".")

# 获取所有锁定的依赖包
locked_packages = poetry.locker.locked_repository().packages

# 自定义易读格式的输出
output_lines = []
for pkg in locked_packages:
    output_lines.append(f"* **{pkg.name}** ({pkg.version})")
    if pkg.description:
        output_lines.append(f"  {pkg.description.strip()}")
    output_lines.append("")

full_output = "\n".join(output_lines)

with open("poetry_deps_readable.txt", "w", encoding="utf-8") as f:
    f.write(full_output)

第三种方法无需调用外部命令,直接从Poetry内部获取数据,不仅不会出现输出截断,还能根据你的需求灵活调整输出格式,完美适配你生成易读配套文件的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:05:09