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

Python如何将subprocess返回的输出转换为字典列表

转换输出为字典列表的实现方案

核心问题说明

你当前拿到的是bytes类型的Python字面量结构输出,JSON标准要求键值用双引号,直接用JSON解析会报错,推荐用更适配的ast.literal_eval处理。

推荐实现代码(安全稳定版)

import subprocess
import ast

chief_complaint = "Eernise, Randell is an 64-year-old male"
# 改用列表形式传参,避免shell注入风险,无需额外处理引号转义
command = ["python", "predict_icd.py", "--cc", chief_complaint]
command_proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 统一读取标准输出和错误输出,避免缓冲区阻塞
stdout, stderr = command_proc.communicate()

# 步骤1:将bytes输出解码为字符串,去除首尾空白字符
result_str = stdout.decode('utf-8').strip()
# 步骤2:解析Python字面量为字典列表
result_list = ast.literal_eval(result_str)

# 测试验证:打印首个元素的text字段
print(result_list[0]['text'])

备选方案(JSON适配版)

如果业务场景中确定输出内容不含单引号,也可以替换引号后用json库解析:

import subprocess
import json

chief_complaint = "Eernise, Randell is an 64-year-old male"
command = ["python", "predict_icd.py", "--cc", chief_complaint]
command_proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = command_proc.communicate()

result_str = stdout.decode('utf-8').strip().replace("'", '"')
result_list = json.loads(result_str)

原代码优化点说明

  • 去掉shell=True参数改用列表传参,避免命令注入风险,同时解决特殊字符转义问题
  • 用communicate()统一读取输出,避免子进程缓冲区满导致卡住的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:45:03