文章目录
概要
python和node之间通信,node 主要通过python-shell中的options传参给python文件,python文件通过sys.argv接收options内的参数
1.python页面
通过sys获取返回的数据
# index.py
#import numpy as np
#raw=np.fromfile(r'C:\Users\admin\Desktop\electron_plane\daw\1.raw',dtype='uint16')
# print(raw)
import sys // 引入sys模块获取node传来的数据
// sys.argv获取node传来的参数options.args
print(sys.argv) // 打印获取的数据(node页面接收print返回的数据)
// 返回数据为 ['\electron_plane\daw\1.raw',10,10]
2.node页面
// index.vue
// 引入vue插件 (python-shell) npm install python-shell
import { PythonShell } from "python-shell";
// 设置Python脚本文件路径
const scriptPath = "./src/components/index.py";
// 设置传递给Python脚本的参数
const args = [C:\Users\admin\Desktop\electron_plane\daw\1.raw, 10, 10];
// 配置PythonShell
const options = {
pythonPath: "python", // 设置Python解释器的路径
args: args, // 设置传递给Python脚本的参数
};
// 创建PythonShell实例
const pyshell = new PythonShell(scriptPath, options);
// 监听Python脚本的输出(接收python文件中print的输出)
pyshell.on("message", function (message) {
console.log(message);
});
// 监听Python脚本执行完成事件
pyshell.on("close", function () {
console.log("Python脚本执行完成。");
});
}