在Nodejs中使用PythonShell模块

2024-06-06 18:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试图遵循npm pythonshellhere的文档。我只是想得到一个简单的例子来正确地工作,但没有成功,网上没有很多例子,但我确实试着遵循这个one on stackoverflow。那么我的代码到底怎么了?我不太清楚为什么我会犯下面的错误。我对python更熟悉,nodejs对我来说是一个新领域。谢谢你的帮助。

test.py代码:

print("This is a test")

使用pythonsell测试的Nodejs:

var PythonShell = require('python-shell');

    var options = {
      mode: 'text',
      pythonPath: '/bin/bash/python2', 
      pythonOptions: ['-u'],
      scriptPath: './TestProject/',
      args: ['value1', 'value2', 'value3']
    };

    PythonShell.run('test.py', options, function (err, results) {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });

这是我的错误

    internal/child_process.js:313
    throw errnoException(err, 'spawn');
    ^

Error: spawn ENOTDIR
    at exports._errnoException (util.js:1022:11)
    at ChildProcess.spawn (internal/child_process.js:313:11)
    at exports.spawn (child_process.js:387:9)
    at new PythonShell (/home/nomad/TestProject/node_modules/python-shell/index.js:59:25)
    at Function.PythonShell.run (/home/nomad/TestProject/node_modules/python-shell/index.js:159:19)
    at Object.<anonymous> (/home/nomad/TestProject/app.js:11:13)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)

Tags: testchildhomejsshellprocessresultsat
1条回答
网友
1楼 · 发布于 2024-06-06 18:58:22

因此,我犯了一个错误,没有在新的系统安装中检查python路径,但是使用绝对路径也是脚本运行的必要条件。下面是一个工作示例,供任何试图使用nodejs python shell npm运行python脚本的人使用。感谢Bryan帮助我处理javascript错误。

var PythonShell = require('python-shell');

    var options = {
      mode: 'text',
      pythonPath: '/usr/bin/python', 
      pythonOptions: ['-u'],
      // make sure you use an absolute path for scriptPath
      scriptPath: '/home/username/Test_Project/Python_Script_dir',
      args: ['value1', 'value2', 'value3']
    };

    PythonShell.run('test.py', options, function (err, results) {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });

相关问题 更多 >