网站首页 > 基础教程 正文
Node.js比较适合执行IO密集的操作,不擅长数据处理等CPU密集的操作。
而Python则比较擅长数据处理,且有很多好用的工具和计算库。
用Node调用Python,就成为一种不错的实用组合,在日常工作中是非常有用的。
?
??
?
这里简单记录一下,Node如何调用Python。使用Node的child_process?库,可以创建并管理子进程。其具体函数为spawn?。
Node示例代码如下:
const spawn=require('child_process').spawn
const py = spawn('python',['a.py'])
console.log('start…………')
py.stdout.on('data',function(res){
let data = res.toString();
console.log('stdout: ',data)
})
py.stderr.on('data',function(res){
let data = res.toString();
console.log('stderr: ',data)
})
py.on('close', (code) => {
console.log(`子进程退出:退出代码code ${code}`);
});
console.log('end.')
调用的Python脚本a.py代码如下:
import time
print('python start',flush=True)
time.sleep(10) #等待10秒
print('python end',flush=True)
?
用Node执行js脚本后,由于js都是异步操作,因此会执行语句打印“start…………”和“end.”。
Node父进程会等待Python子进程执行完成。
因为监听了stdout,当Python子进程打印到stdout的内容,会被Node父进程接受并显示。
因为监听了close消息,当Python子进程退出时,Node父进程也会监听到退出信号。
??
使用Node.js调用Python,一定程度上可以弥补Node.js缺乏计算密集能力的不足。同样的方式,也可以形成Node.js+Java等组合,进一步扩大了Node.js的使用范围。
?
参考:
child_process 子进程 | Node.js API 文档 (nodejs.cn)
?
猜你喜欢
- 2024-11-25 Deno 1.30 正式发布
- 2024-11-25 用 WasmEdge 和 Rust 在边缘云上构建高性能且安全的微服务
- 2024-11-25 通过浏览器工作台启动本地项目
- 2024-11-25 r2frida:基于Frida的远程进程安全检测和通信工具
- 2024-11-25 NPM 使用介绍
- 2024-11-25 使用Hexo在github上搭建静态博客
- 2024-11-25 Android动态调试(1)-Radare2和lldb
- 2024-11-25 Metasploit渗透测试之MSFvenom
- 2024-11-25 浅析CTF中的Node.js原型链污染
- 2024-11-25 首个SSRF漏洞开篇学习
- 06-09Socioeconomic growth goals high on meetings' agenda
- 06-09Cities Along Middle Reaches of Yangtze River Agree on 63 Cooperation Items
- 06-09Scientists to make flag flutter on moon
- 06-09CBN丨Foreign-funded institutions bullish on Chinese assets
- 06-09Full Text: Joint Statement between the People's Republic of China and the French Republic on Climate Change on the occasion of the Tenth Anniversary of the Paris Agreement
- 06-092022年底总结,温暖和激励自己的文案
- 06-09百度实时推送代码解决方案(百度实时推送工具)
- 06-09PHP漏洞之跨网站请求伪造(php跨站脚本攻击)
- 最近发表
-
- Socioeconomic growth goals high on meetings' agenda
- Cities Along Middle Reaches of Yangtze River Agree on 63 Cooperation Items
- Scientists to make flag flutter on moon
- CBN丨Foreign-funded institutions bullish on Chinese assets
- Full Text: Joint Statement between the People's Republic of China and the French Republic on Climate Change on the occasion of the Tenth Anniversary of the Paris Agreement
- 2022年底总结,温暖和激励自己的文案
- 百度实时推送代码解决方案(百度实时推送工具)
- PHP漏洞之跨网站请求伪造(php跨站脚本攻击)
- ThinkPHP后台入口地址查找(thinkphp build.php)
- PHP新手如何提高代码质量(php新手如何提高代码质量的方法)
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)