最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

将JSON片段从NodeJS发送到Python,对其进行处理并将其发送回NodeJS

网站源码admin15浏览0评论

将JSON片段从NodeJS发送到Python,对其进行处理并将其发送回NodeJS

将JSON片段从NodeJS发送到Python,对其进行处理并将其发送回NodeJS

我想将JSON数据从Node.js发送到Python。 Python程序会处理这些数据,然后将其发送回Node.js。我在这里使用了PythonShell模块。

const json_content = JSON.parse(originalContent); // parses the json file

let options = { // setting the options for the python-shell
    mode: 'text',
    pythonPath: ".\python.exe",
    pythonOptions: ['-u'], 
    scriptPath:  ".\\src\\",
};

const python_script1 = new PythonShell('test.py', options);

for (i=0; i <= json_content['SMTH'].length; i++) {

    python_script1.send(JSON.stringify(json_content['SMTH'][i]));
    python_script1.on('message', (message) => { 
    console.log(message);  
    });

    python_script1.end( (err) => {
        if (err) { throw err};
        console.log('finished');
    });
   };

我的Python文件看起来像这样:

def main():

    lines = sys.stdin.readlines()

    print(lines)
    json_dict1=  json.loads(lines[0])
    print(json_dict1)

    return lines

if __name__ == "__main__":
    main()

但是,它不起作用。我的目标是遍历JSON文件并将其发送到Python的每个部分。我如何实现它的工作原理,并异步工作->发送数据->接收数据->然后发送下一个数据?

如果我调试,则始终发出事件侦听器(console.log(message))中的python_script1.on

JSON-示例:

{
   "SMTH":[
      {
         "LOG":"FL",
         "TYPE":"REL",
         "UIN":"BROKER_CTRL.MyBroker.Processing.sp_SingleProc",
         "VALUE":1,
         "TIMESTAMP":1,
         "EXPERIMENT":0
      },
      {
         "LOG":"FL",
         "TYPE":"REL",
         "UIN":"BROKER_CTRL.MyBroker.Processing.sp_SingleProc",
         "VALUE":-1,
         "TIMESTAMP":2,
         "EXPERIMENT":0
      },
      {
         "LOG":"FL",
         "TYPE":"REL",
         "UIN":"BROKER_CTRL.MyBroker.Processing.sp_SingleProc",
         "VALUE":1,
         "TIMESTAMP":3,
         "EXPERIMENT":0
      },
      {
         "LOG":"FL",
         "TYPE":"REL",
         "UIN":"BROKER_CTRL.MyBroker.Processing.sp_SingleProc",
         "VALUE":-1,
         "TIMESTAMP":4,
         "EXPERIMENT":0
      },
      {
         "LOG":"FL",
         "TYPE":"REL",
         "UIN":"BROKER_CTRL.MyBroker.Processing.sp_SingleProc",
         "VALUE":1,
         "TIMESTAMP":5,
         "EXPERIMENT":0
      }
   ]
}
回答如下:

我看到您正在为其使用模块PythonShell,我认为可以避免,并且可以以更简单的方式完成。为什么不运行bash命令直接从Node.js代码运行python脚本,这将使您对代码有更多的控制。下面是插图

const { exec } = require('child_process');
function runBashCommand(command) {
    return new Promise((resolve, reject) => {
        exec(command, (err, result) {
            if(err) return reject(err.message)
            return resolve(result)
        })
    })
}

现在,您的主要Nodejs代码可以使用您将给它的python命令调用上面的函数,>]

python test.py arg1

并且您的主要代码在下面,

const json_content = JSON.parse(originalContent);
async function transform()
for (i=0; i <= json_content['SMTH'].length; i++) {
    try {
       let commandToRun = `python test.py ${JSON.stringify(json_content['SMTH'][i])}`
       let result = await runBashCommand(commandToRun);
       console.log(result);
    } catch(err) {
        console.error(err.message)
     }
}

我希望这将在没有任何依赖的情况下正确完成您的工作。

谢谢!

发布评论

评论列表(0)

  1. 暂无评论