首页 > 解决方案 > 我想在 Node.js 中调用 Python 并使用 SymPy 模块

问题描述

我使用 Node.js 和 Express 作为服务器端语言。
我使用 AWS 创建了一个网站。

我需要使用 Python,因为我需要复杂的计算。
但是,我不知道如何从 Node.js 调用 Python。

请告诉我如何在 Node.js 中使用 Python 的 SymPy 模块。

标签: javascriptpythonnode.jsexpresssympy

解决方案


如果您需要从 Node.js 应用程序调用外部脚本,您始终可以生成一个进程来执行此操作。

(显然)有一个 npm 模块可以让您更轻松地使用来自 Node.js 的 python 脚本。如果您无法在 Node.js 生态系统中找到等价物,您可以使用python-shell模块来启动您的“复杂计算”脚本。

这是一个受SymPy和 python-shell 文档启发的基本示例:

脚本.py

from sympy import *

x = Symbol('x')
print (limit(sin(x)/x, x, 0))

应用程序.js

const {PythonShell} = require('python-shell');

PythonShell.run('script.py', null, function (err, res) {
  if (err) throw err;
  console.log(res[0]);  // 1
});

还要注意在你的路径中有 SymPy 模块。


推荐阅读