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
相关产品推荐
相关产品推荐

