简体   繁体   English

NodeJS stdout python多次打印?

[英]NodeJS stdout python multiple prints?

I have a python script that prints JSON and string: 我有一个打印JSON和字符串的python脚本:

# script.py
print('{"name": "bob", "height": 4, "weight": 145}')
print('hello')
sys.stdout.flush()

A nodejs app calls the python script via child-process . nodejs app通过child-process调用python脚本。 But I'm getting error on the output. 但是我输出错误了。 How can I process the python output in nodejs? 如何在nodejs中处理python输出?

// nodejs
var process = spawn('python3', ["./script.py", toSend]);
    process.stdout.on('data', function(data) {
      message = JSON.parse(data)
      console.log(message)
})

I'm getting this a SyntaxError: Unexpected token from running this. 我得到一个SyntaxError: Unexpected token运行它的SyntaxError: Unexpected token

In your python script... This line 在你的python脚本中...这一行

print('{"name": "bob", "height": 4, "weight": 145}')

should be changed 应该改变

import json
print(json.dumps({"name": "bob", "height": 4, "weight": 145}))

That will handle and make sure the JSON is formatted correctly, so that the JSON string can be parsed by node (but your current version should be fine). 这将处理并确保正确格式化JSON,以便节点可以解析JSON字符串(但您当前的版本应该没问题)。 However in this case the real problem is what follows... 但是在这种情况下,真正的问题是......

You are ending your script with 你正在用你的脚本结束

print('hello')

which means that JSON.parse() is going to try and parse hello as part of the JSON.parse() because you are reading from stdout... hello is not JSON formatted. 这意味着JSON.parse()将尝试解析hello作为JSON.parse()的一部分,因为您正在从stdout读取... hello不是JSON格式的。 So JSON.parse() is going to fail. 所以JSON.parse()将会失败。 So remove that line as well. 所以也删除该行。

If you have more then one json object to send as you stated in your comments 如果您在评论中说明有多个json对象要发送

You can either combine all the data into a single JSON object my_object = {"data": "info"....} and json.dumps() that single larger object.. 您可以将所有数据组合成单个JSON对象my_object = {"data": "info"....}json.dumps()这个单个较大的对象。

or 要么

obj1 = {}
obj2 = {}
myobjects = [obj1, obj2]
print(json.dumps(myobjects))

and the Node side will recieve a list of objects that can be iterated on 并且Node端将接收可以迭代的对象列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM