【问题标题】:How to include python script inside a NodeJS file?如何在 NodeJS 文件中包含 python 脚本?
【发布时间】:2017-04-06 16:37:35
【问题描述】:

大家好,

通过这个社区的推荐,我已经将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 相同的文件中的脚本中。

这个运行在nodejs上的应用会通过electron打包成一个可执行的桌面应用。

【问题讨论】:

    标签: python node.js python-3.x serial-port electron


    【解决方案1】:

    我认为将 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

    这样,你就需要关心命令注入漏洞了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 2019-08-27
      • 2013-07-05
      • 2012-06-05
      • 1970-01-01
      相关资源
      最近更新 更多