为了账号安全,请及时绑定邮箱和手机立即绑定

无法从 Node.js 运行 python 文件

无法从 Node.js 运行 python 文件

慕勒3428872 2023-09-02 16:38:36
我有一个 Python 文件,其中包含 ML 模型,当我与 cmd 分开运行它时,它运行良好。每当我在特定路线上发布时,我目前都尝试从节点运行它。但是,到目前为止,我还无法运行 python 脚本。到目前为止,我已经在节点中使用了两个模块,我已经使用了child_process,我还使用了@fridgerator/pynode。1- @fridgerator/pynode 出现的问题是它不断给出错误 ModuleNotFoundError: No module named 'team_match_prediction3' 无法加载模块: team_match_prediction3team_match_prediction3 是我与 node.js 文件一起放置的 python 文件名:以下是带有 @fridgerator/pynode 模块的 Node.js 路由的代码:router.post(("/team"),(req, res) =>{let regressionModel = {};pynode.startInterpreter();pynode.appendSysPath('./');pynode.openFile('team_match_prediction3');    let team_1 = req.body.Team1;    let team_2 = req.body.Team2;    new Promise((resolve, reject) => {        try {          if (_.isEmpty(regressionModel)) {            console.log('calling python');            regressionModel = pynode.call('starting_func',team_1, team_2);          }          resolve(regressionModel);        } catch(err) {          console.log(err);          reject('failed to load Teams variables');        }    })    .then(response => res.send(response))    .catch(err => res.err(err));});我从这个网站找到了这个 pynode 代码片段:https://thecodinginterface.com/blog/bridging-nodejs-and-python-with-pynode/2-然后我使用了子进程模块,该模块出现的问题是,stdout.on (“data”)方法没有运行,它甚至不会等待python脚本完成并运行python.on ('close')函数。这是 child_process 部分的 node.js 代码://The import const {spawn} = require('child_process');router.post(("/team"),(req, res) =>{ let team_1 = req.body.Team1;    let team_2 = req.body.Team2;    const python = spawn('python', ['./team_match_prediction3.py' , team_1,team_2]);    let dataToSend = [];    python.stdout.on('data', (data) => {        console.log('Pipe data from python script ...');        dataToSend.push(data);       });当我使用子进程模块时,它只给出一个 console.log 该进程以 pid 2 结束,这几乎立即发生,并且不发送任何数据作为响应。关于python文件,对于pynode模块,我刚刚创建了一个由pynode调用的函数,该函数仅调用clean_and_predict函数,该函数仅返回所需的数据,Final_answer 是一个字典,其中 Winner 是获胜板球队的名称。任何有关如何解决此问题或是否应使用新模块的想法将不胜感激,谢谢。
查看完整描述

1 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

我能够解决这个问题,首先,我通过提供存储 server.js 文件的文件夹的路径而不是调用 python 文件的路由器文件来部分解决了文件未找到错误。


另一个问题是等待 python 文件执行并从中获取结果,我使用 npm 模块 execa 来执行此操作,


这是调用并等待 python 文件的节点部分:



    const execa = require('execa');


然后在帖子路由中:



      

let team_1 = req.body.Team1;

let team_2 = req.body.Team2;



  const subprocess = execa('python 

path/to/pythonfile/from/serve.js/folder', [team_1,team_2]);

  subprocess.stdout.pipe(process.stdout);


  (async () => {

    const {stdout} = await subprocess;

    // Returning Result: 

    res.send(stdout);

    console.log('child output:', stdout);

})();


查看完整回答
反对 回复 2023-09-02
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信