如何从node.js调用外部脚本/程序
How to invoke external scripts/programs from node.js
我有一个C++
程序和一个Python
脚本,我想将其合并到我的node.js
Web 应用程序中。
我想使用它们来解析上传到我的网站的文件;处理可能需要几秒钟,所以我也会避免阻止该应用程序。
我怎样才能只接受文件,然后从node.js
控制器在子进程中运行C++
程序和脚本?
请参阅child_process.下面是一个使用spawn
的示例,它允许您写入stdin并在输出数据时从stderr/stdout读取。如果您不需要写入 stdin,并且可以在进程完成后处理所有输出,child_process.exec
提供了稍短的语法来执行命令。
// with express 3.x
var express = require('express');
var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
app.post('/upload', function(req, res){
if(req.files.myUpload){
var python = require('child_process').spawn(
'python',
// second argument is array of parameters, e.g.:
["/home/me/pythonScript.py"
, req.files.myUpload.path
, req.files.myUpload.type]
);
var output = "";
python.stdout.on('data', function(data){ output += data });
python.on('close', function(code){
if (code !== 0) {
return res.send(500, code);
}
return res.send(200, output);
});
} else { res.send(500, 'No file found') }
});
require('http').createServer(app).listen(3000, function(){
console.log('Listening on 3000');
});
可能是一个老问题,但其中一些参考将提供更多细节和在 NodeJS 中包含 python 的不同方法。
有多种方法可以做到这一点。
- 第一种方法是做
npm install python-shell
这是代码
var PythonShell = require('python-shell');
//you can use error handling to see if there are any errors
PythonShell.run('my_script.py', options, function (err, results) {
//your code
您可以使用以下方法向 Python Shell 发送消息 pyshell.send('hello');
您可以在此处找到 API 参考-https://github.com/extrabacon/python-shell
第二种方式 - 你可以参考的另一个包是 节点 python ,你必须做
npm install node-python
第三种方式 - 您可以参考这个问题,您可以在其中找到使用子进程的示例-如何从节点调用外部脚本/程序.js
更多参考资料 -https://www.npmjs.com/package/python
如果要使用面向服务的体系结构 -http://ianhinsdale.com/code/2013/12/08/communicating-between-nodejs-and-python/
- 如何通过cpp程序运行shell脚本
- 在函数内部的声明中初始化数组,并在外部使用它
- 使外部项目可用于find_package CMake
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- 在程序中编写脚本来编写和编译代码
- C++:来自外部文件的Trivia
- 从函数角度看ID到文件路径的内部与外部映射
- C++:将外部库链接到dll库
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 节俭并发:未解决的外部问题
- 如何在c++中从git建立外部库
- 如何在c++中使用system()来运行包含空格的python脚本
- 未解析的外部符号_MsiLocateComponentW@12.
- 如何使用来自外部脚本的回调发送信号
- 如何在没有外部脚本的情况下链接CMake和SQLite
- 如何从node.js调用外部脚本/程序
- 将外部进程的输出管道传输到正在运行的脚本C++
- Qt调用外部Python脚本
- 调用一个外部C++函数,Memory Leaks:将在完成Python脚本后清理所有分配的内存