electron中用nodejs调用python生成netcdf格式文件

背景

  • 奇葩的项目需求,由于需要生成netcdf格式文件,于是特意去查了查,这家伙,老复杂了,是一种标准协议,用来存储气象相关信息的。
  • 打开了github开始搜索相关库,c的,java的,python的,然后没了?没有nodejs版本的,去官网看了看,看来真的没有,于是向后端寻求帮助,结果我们的后端只会go和c#,事情一度卡在那里。我甩给后端,后端说做不了,没他熟悉的语言。我说这个前端也没有相应的库我也做不了。
  • 后来老大直接下了死命令,说什么也要搞出来,于是一番博弈过后,苦差事落在了我的头上,于是再语言里面选择了最容易入门的python,开始自己学,学一点毛皮

node 模块child_process的exce

  • node 拥有子进程这个概念,父进程可以额外的执行子进程,并能监听子进程的状态
  • 子进程可以执行终端指令,这也是我们的突破口,利用子进程执行终端命令,利用终端命令来执行python文件
  const exec = require("child_process").exec;
  exec(`C:\\Users\\xuji\\AppData\\Local\\Programs\\Python\\Python310\\python.exe "${path.resolve(getPath('/writeNC.py'))}"`,(err,s,a)=>{
         // ----业务逻辑--- //
        })

python 的实现

  • 由于是终端执行的python命令,好多参数拼接会有问题,于是采用了读本指定路径下json文件的方式去读取数据,并且读取最终产物写入位置
  • 具体流程为:判断环境=》读取json文件=》解析处理json格式为python可用=》利用netCDF4创建文件=》文件数据写入=》完成
for name in data:
    # print(name,'name')
    nc_fid2=Dataset(name['path'] + "/test"+ str(i) + '.nc', 'w',format="NETCDF3_CLASSIC")
    nc_fid2.createDimension('FloatA',len(name["FloatA"]))
    nc_fid2.createDimension('FloatB',len(name["FloatB"]))
    nc_fid2.createDimension('FloatC',len(name["FloatC"]))
    nc_fid2.createDimension('FloatD',len(name["FloatD"]))
    nc_fid2.createDimension('FloatE',len(name["FloatE"]))
    nc_fid2.createDimension('depth',1)
    nc_fid2.createDimension('time',1 )
    nc_fid2.createDimension('aa',1 )

    #额外参数
    nc_fid2.TimeAt = name['TimeAt']
    nc_fid2.HAngle = name['HAngle']
    nc_fid2.VAngle = name['VAngle']
    nc_fid2.BeginAngle = name['BeginAngle']
    nc_fid2.EndAngle = name['EndAngle']
    nc_fid2.Longitude = name['Longitude']
    nc_fid2.Latitude = name['Latitude']
    nc_fid2.Humidity = name['Humidity']
    nc_fid2.BeginAngle = name['BeginAngle']
    
    #创建文件变量
    FloatA_Arys = nc_fid2.createVariable('FloatA', 'f4', ('FloatA',))
    FloatB_Arys = nc_fid2.createVariable('FloatB', 'f4', ('FloatB',))
    FloatC_Arys = nc_fid2.createVariable('FloatC', 'f4', ('FloatC',))
    FloatD_Arys = nc_fid2.createVariable('FloatD', 'f4', ('FloatD',))
    FloatE_Arys = nc_fid2.createVariable('FloatE', 'f4', ('FloatE',))
    depth = nc_fid2.createVariable("depth","f8",("depth",))
    times = nc_fid2.createVariable("time","f8",("time",))
	#参数复制 
    FloatA_Arys[:] = name["FloatA"][:]
    FloatB_Arys[:] = name["FloatB"][:]
    FloatC_Arys[:] = name["FloatC"][:]
    FloatD_Arys[:] = name["FloatD"][:]
    FloatE_Arys[:] = name["FloatE"][:]
    nc_fid2.close()
    i = i + 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以通过两种方式将 ElectronPython 集成: 1. 通过 Python Shell 模块:Python Shell 是一个 Node.js 模块,它可以通过子进程执行 Python 脚本。你可以在 Electron 中使用它来调用 Python 脚本。在你的 Electron 项目中安装 Python Shell 模块: ``` npm install python-shell ``` 然后在 Electron 中使用它: ```javascript const {PythonShell} = require('python-shell'); PythonShell.run('my_script.py', null, function (err, results) { if (err) throw err; console.log('results: %j', results); }); ``` 2. 通过 Python 的网络接口:在 Python 中启动一个 web 服务器,并在 Electron 中使用 Node.js 的 HTTP 模块发送请求。这种方法需要 Python 程序员编写一个 Python web 服务器,以便 ElectronPython 之间进行通信。在 Python 中启动 web 服务器: ```python from http.server import BaseHTTPRequestHandler, HTTPServer import json class RequestHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) json_data = json.loads(post_data.decode('utf-8')) # 获取传入的参数 arg1 = json_data['arg1'] arg2 = json_data['arg2'] # 调用 Python 函数 result = my_function(arg1, arg2) # 返回结果 response = {'result': result} self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps(response).encode('utf-8')) def run(): httpd = HTTPServer(('localhost', 8080), RequestHandler) httpd.serve_forever() if __name__ == '__main__': run() ``` 在 Electron调用 Python 函数: ```javascript const http = require('http'); const postData = JSON.stringify({'arg1': 'hello', 'arg2': 'world'}); const options = { hostname: 'localhost', port: 8080, path: '/', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; const req = http.request(options, (res) => { res.on('data', (chunk) => { const result = JSON.parse(chunk)['result']; console.log(result); }); }); req.write(postData); req.end(); ``` 这两种方法都可以在 Electron调用 Python 函数,具体的选择取决于你的需求和技能水平。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

家雀安知鸿鹄志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值