如何在 NodeJS 文件中包含 python 脚本?

How to include python script inside a NodeJS file?

大家好,

通过这个社区的推荐,我已经在我的应用程序文件夹中安装了诸如 npm install shelljs --save 之类的 shelljs。

现在我正在研究如何在我的 nodejs 文件中实现它。

下面是我的nodejs文件

var express = require('express');
var router = express.Router();
var COMPORT = 5;
var command = 'option1';

在此之下,我想包括我的 python 脚本

import serial 
ser = serial.Serial() 
ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate 
// COMPORT is a variable that stores an integer such as 6 
ser.port = "COM{}".format(COMPORT) 
ser.timeout = 10 
ser.open() 
#call the serial_connection() function 
ser.write(("%s\r\n"%command).encode('ascii'))

因此,我的问题是如何将此 python 脚本与 nodejs 中定义的变量一起包含在与 nodejs.js 相同的文件中。

这个运行在 nodejs 上的应用程序将通过 electron 打包为一个可执行的桌面应用程序。

我认为这是将 运行 python 脚本作为子进程的最简单方法。

const childProcess = require('child_process'),
      cmd = './script.py --opt=' + anyValueToPass;

childProcess.exec(cmd, function(err, stdout, stderr) {
  // command output is in stdout
});

阅读更多关于子进程的信息:Execute a command line binary with Node.js

这样就不用担心命令注入漏洞了