【发布时间】:2021-12-13 20:27:40
【问题描述】:
我正在尝试学习如何使用标准输入和标准输出在节点和 Python 之间来回传递数据。
这是一个超级简单的东西,节点app.js 调用Python 文件test.py。
app.js
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python3',["test.py"]);
pythonProcess.stdout.on('data', (data) => {
mystr = data.toString();
myjson = JSON.parse(mystr);
console.log(myjson.Data);
});
test.py
import sys,json
data = {"devices":{
"boiler":{
"address":"12345:2",
"object_type":"analogInput",
"object_instance":"2"
},
"cooling_plant":{
"address":"12345:2",
"object_type":"analogInput",
"object_instance":"2"
},
"air_handler_1":{
"address":"12345:2",
"object_type":"analogInput",
"object_instance":"2"
},
"air_handler_2":{
"address":"12345:2",
"object_type":"analogInput",
"object_instance":"2"
},
"hot_water_valve_1":{
"address":"12345:2",
"object_type":"analogInput",
"object_instance":"2"
}
}}
resp = {
"Response": "Success",
"Message": "from Python string",
"Data": data
}
print(json.dumps(resp))
sys.stdout.flush()
当我运行$ node app 时,我可以在控制台中看到来自 python 脚本的 json 数据。
这里的智慧几乎为零,我的问题是是否可以保留一个“正在运行”的 python 脚本,其中包含一个函数,通过 stdin 和 stdout 我可以将数据从节点传递到正在运行的 Python 脚本函数?
这似乎正是 npm 包 python-shell 可以做到的 from there page。
谁能给我一些建议,告诉我如何传递这样的字符串:
"12345:2 analogInput 2"
让 Python 脚本通过函数返回与使用 `python-shell' 的 json 相同的字符串?
【问题讨论】:
-
所以,基本上你的问题是如何在节点中使用
python-shell执行 Python 脚本(传递输入并使用输出)?或者您的问题是如何使用节点的spawn调用 Python 脚本? -
Python 脚本(传递输入并使用输出)使用 python-shell 正如你提到的。好奇它是否可能让 Python 脚本也保持运行/活着
-
这似乎也将问题混为一谈:运行子进程的节点程序通过标准输入/标准输出与该子进程交换数据。 python 程序作为一个子进程,期望通过标准输入/标准输出与其父进程交换数据。您要问的是哪一个?
-
是的,对不起.....
标签: python node.js stdout stdin