You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从JavaScript调用Python脚本时遇ModuleNotFoundError问题求助

解决Node.js调用Python脚本时的ModuleNotFoundError问题

问题核心

通过Express的index.js调用机器学习模型的index.py脚本时,出现ModuleNotFoundError: No module named 'pandas',调整导入语句位置后其他已安装模块也报相同错误。本质原因是Node.js通过spawn调用的Python环境,和你安装pandas等模块的环境不匹配。

相关代码

index.js

const express = require('express');
const { spawn } = require('child_process');
const app = express();
const port = 3000;

app.get('/predict', (req, res) => {
  // Get the input value from the query parameter
  const inputValue = parseFloat(371);

  // Spawn the Python script with the input value as an argument
  const childPython = spawn('/usr/bin/python3', ['index.py', inputValue.toString()]);

  // Capture the Python script's stdout
  childPython.stdout.on('data', (data) => {
    // Send the prediction back as a response
    res.send(`Prediction: ${data}`);
  });

  // Handle errors
  childPython.stderr.on('data', (data) => {
    console.error(`Error: ${data.toString()}`);
    });
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

index.py

import sys
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
# Load your dataset here
data = pd.read_csv("biomass-biogas.csv")

# Get the input value from the command-line argument
input_value = float(371)  # 注意:此处未读取Node.js传入的参数,需修改

# Your model and data processing code
X = data.drop(['BIOGAS'], axis=1)
y = data['BIOGAS']
feature_names = X.columns.tolist()
X = X.values 
model = DecisionTreeRegressor()
model.fit(X, y)

# Use the input value to make a prediction
prediction = model.predict([[input_value]])

# Print the prediction
print(prediction[0])

错误信息

Error: import pandas as pd
ModuleNotFoundError: No module named 'pandas'


解决方案

方案1:使用正确的Python解释器路径

  1. 在终端执行以下命令,找到你安装了pandas等模块的Python环境路径:
    which python3
    
    输出示例:/usr/local/bin/python3或~/venv/bin/python3
  2. 修改index.js中spawn的Python路径为上述结果,比如:
    const childPython = spawn('/usr/local/bin/python3', ['index.py', inputValue.toString()]);
    

方案2:给目标Python环境安装依赖

如果不确定环境,直接用spawn里指定的Python解释器对应的pip安装模块:

/usr/bin/python3 -m pip install pandas scikit-learn

(将/usr/bin/python3替换为你实际使用的Python路径)

方案3:使用虚拟环境(推荐,避免环境冲突)

  1. 进入index.py所在目录,创建虚拟环境:
    python3 -m venv venv
    
  2. 激活虚拟环境:
    • Linux/macOS:source venv/bin/activate
    • Windows:venv\Scripts\activate
  3. 在激活的环境中安装依赖:
    pip install pandas scikit-learn
    
  4. 修改index.js中的Python路径为虚拟环境内的解释器:
    const childPython = spawn('./venv/bin/python3', ['index.py', inputValue.toString()]);
    

额外修复:Python脚本读取命令行参数

当前index.py中直接写死了input_value = float(371),未读取Node.js传入的参数,需修改为:

input_value = float(sys.argv[1])

内容的提问来源于stack exchange,提问作者SATHVIK SVS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:07:13