在 Node.JS 环境中安装 node-python 包就可以让 Python 代码在 Node.JS 中执行. 安装命令为 NPM install node-python.
Node.JS 中执行 Python 代码的详细方法:
下面说一下安装方式, 步骤包括了 Node.JS 的安装
先安装 Node.JS 环境:
Mac
进入 Node.JS.org, 点击'install', 执行整个安装过程.
Ubuntu
在命令行运行下面的代码去安装为 Node.JS 准备的源代码
curl -sL https://deb.nodesource.com/setup | sudo -E bash -
然后运行下面的代码获得最新的 Node.JS 包
- sudo apt-get install -y Node.JS
- Windows
直接下载 Windows 安装包 Windows binary 运行安装.
测试一下
在命令行敲入下面的代码来检查 Node.JS 环境和 NPM 环境是否正常
node -v NPM -v
安装 node-python
NPM install node-python
在命令行中输入上面的命令, 把这个 NPM 包添加到您的本地机器上,. 你会注意到一个 node_modules 目录现在出现在你的根目录, 那个就是 node 模块文件夹.
其它有用的命令
NPM init: 在你的当前目录下创建一个 package.JSON 文件
NPM list: 列出所有已经安装了的包
NPM prune: 根据你的 package.JSON 文件, 移除项目中安装过的不需要的包
NPM outdated: 运行这个命令将会告诉你你安装的包中哪些是过时的.
在 Node.JS 中执行 Python
- // python 部分
- var python = require('node-python');
- var os = python.import('os');
- // Node.JS 部分
- var path = require('path');
- // 用 assert 来检查一下, 通过 python 获得的内容是否和通过 node 获得的内容是否相同
- assert(os.path.basename(os.getcwd()) == path.basename(process.cwd()))
来源: http://www.css88.com/qa/node-js/12095.html