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

如何在Python端接收Node.js通过python-shell发送的JSON并转为字典?

解决Node.js向Python定时发送JSON数据并在Python端解析为字典的问题

我来帮你搞定这个问题!你的Node.js脚本已经用node-schedule实现了定时任务,并且通过python-shell的json模式准备发送数据,现在只需要在Python端处理输入流,把接收到的JSON转换成字典即可。

先优化下Node.js端的代码(避免潜在问题)

你的原代码里如果res不是当前作用域内的变量(比如非Express场景)会报错,而且如果把pyshell实例放在定时任务外,第一次end()后连接就关闭了,下次定时触发时send()会失败。建议每次定时任务创建新的PythonShell实例:

const schedule = require('node-schedule');
const PythonShell = require('python-shell');

// 设置定时时间
let d = new Date('2018-04-16 10:16:10');

let j = schedule.scheduleJob(d, () => {
  // 每次任务创建新的PythonShell实例,确保通信正常
  const pyshell = new PythonShell('../a.py', { mode: 'json' });
  
  // 发送JSON数据
  pyshell.send({ test: 1, ff: 2 });
  
  pyshell.end(err => {
    if (err) {
      console.error("执行Python脚本出错:", err);
    } else {
      console.log("数据已成功发送给Python");
    }
  });
});

Python端接收并解析JSON为字典的代码

因为python-shell的mode: 'json'会把JS对象序列化为JSON字符串,每行一条发送到Python的标准输入(stdin),所以我们只需要读取stdin的内容,用json模块解析即可:

import json
import sys

# 逐行读取Node.js发送的JSON数据
for line in sys.stdin:
    # 去除换行符和空白字符,解析为Python字典
    try:
        data_dict = json.loads(line.strip())
        # 现在data_dict就是你要的字典,可以直接操作
        print("接收到的字典数据:", data_dict)
        print("test字段的值:", data_dict['test'])
        print("ff字段的值:", data_dict['ff'])
    except json.JSONDecodeError as e:
        print("解析JSON出错:", e)

原理说明

  1. Node.js端:python-shell的json模式会自动把你发送的JS对象序列化为JSON字符串,然后添加换行符发送到Python进程的标准输入。
  2. Python端:通过sys.stdin读取输入流,逐行处理(因为每个send()对应一行JSON),用json.loads()将JSON字符串转换为Python字典,之后就可以像操作普通字典一样使用这些数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:03:27