【发布时间】:2020-09-16 16:06:48
【问题描述】:
我正在开发一个将使用 python 模型的 Web 应用程序。我也为 python 模型创建了环境。但是我面临的问题是我不知道如何通过节点 js 执行该 python 环境,因为我正在使用节点.js 在后端。
【问题讨论】:
-
你在使用 spyder 吗?
标签: python node.js web-development-server
我正在开发一个将使用 python 模型的 Web 应用程序。我也为 python 模型创建了环境。但是我面临的问题是我不知道如何通过节点 js 执行该 python 环境,因为我正在使用节点.js 在后端。
【问题讨论】:
标签: python node.js web-development-server
你可以在nodejs里面运行python virtual environment,你需要从你安装python虚拟环境的bin目录调用python环境,然后你可以使用child_process在nodejs里面运行python代码,看这个例子:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
const { spawn } = require('child_process');
const pyProg = spawn('~/py3env/bin/python', ['test.py']);
pyProg.stdout.on('data', function(data) {
console.log(data.toString());
res.write(data);
res.end('end');
});
})
app.listen(3000, () => console.log('listening on port 3000'))
即使你可以使用shelljs 执行命令行,此时你也可以运行pm2:看这个:
const shell = require('shelljs');
shell.exec('pm2 start test.py --interpreter=./py3env/bin/python', function(code, output) {
console.log('Exit code:', code);
console.log('Program output:', output);
});
【讨论】:
设置好你的python虚拟环境后,你可以在node js中使用PythonShell
首先通过此命令将 PythonShell 安装到您的项目中
npm install python-shell --save
那么你可以通过以下方式在你的js文件中调用python脚本
const path = require('path');
const { PythonShell } = require("python-shell");
// this is your current folder
const py_path = path.join(__dirname, '');
// this is your folder with python environment in it
const python_exe_path = path.join(__dirname, 'python_env/scripts/python.exe');
// then create your python shell options
const py_shell_options = {
mode: 'text',
pythonPath: python_exe_path,
pythonOptions: ['-u'], // get print results in real-time
scriptPath: py_path
// args: ['value1', 'value2', 'value3']
};
// now you can initialize your shell and ready to use it
const pyshell = new PythonShell('py_scripts/my_script.py', py_shell_options);
// sends a message to the Python script via stdin
pyshell.send('hello');
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
});
就是这样,请从官方site阅读更多关于PythonShell的信息
【讨论】: