背景

由于不同语言各有优势,所以有时候会用不同的语言去写不同的脚本,这次写的软件中涉及到爬虫的部分用python写的,主程序用electron+vue的方式写的,所以使用了child_process来调用python打包的exe

方法

node中有一个child_process可以用来创建子进程,这里我就用该功能进行exe的调用,具体方法如下

const cp = require('child_process')
let child = cp.spawn('./exename.exe',[param])

child_process有多种调用方法,详情见:node文档的child_process部分

异步进程的创建
在 Windows 上衍生 .bat 和 .cmd 文件
	child_process.exec(command[, options][, callback])
	child_process.execFile(file[, args][, options][, callback])
	child_process.fork(modulePath[, args][, options])
	child_process.spawn(command[, args][, options])
	options.detached
	options.stdio
同步进程的创建
	child_process.execFileSync(file[, args][, options])
	child_process.execSync(command[, options])
	child_process.spawnSync(command[, args][, options])

常用的主要事件如close等,可以直接用on监听如:

child.on('close',(res)=>{})

监听返回值,返回值要进行fromCharCode解码

child.stdout.on('data',(data)=>{
   for (var i = 0; i < data.length; i++) {
    exeMsg += String.fromCharCode(data[i]);
 }

不过对于从子进程中获取实时返回值,我多次尝试无效,后来只能采用临时文件的方式进行处理,可以在如下的案例中看出

案例

在我的案例中

const cp = require('child_process')
 let child = cp.spawn('./e5/e5.exe',[file])
 this.int=setInterval(that.readProcess,300);
 child.on('close', (stderr) => {
   that.proStr="就绪"
   fs.writeFile('pr.xw', "...", function(err){});
   clearInterval(that.int)
   that.ReadData()
 })
  // child.stderr.on('data', (stderr) => {
        //   console.log(stderr)
        // })
        // child.stdout.on('data',(data)=>{
        //   for (var i = 0; i < data.length; i++) {
        //     exeMsg += String.fromCharCode(data[i]);
        //   }

由于实时获取返回值的尝试未果,使用临时文件和定时任务来获取信息,这个方式有很多问题,但是目前项目比较紧,就先将就着用这个方式了。

Logo

前往低代码交流专区

更多推荐