首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从node.js调用python脚本

从node.js调用python脚本
EN

Stack Overflow用户
提问于 2015-03-01 13:38:09
回答 4查看 3.1K关注 0票数 0

我想从node.js调用python脚本

这是我的脚本: my.py

代码语言:javascript
运行
复制
def printme( str ):
# print str;
return str;
printme("I'm first call to user defined function!");
printme("Again second call to the same function");

我的节点脚本: testpy.js

代码语言:javascript
运行
复制
var PythonShell = require('python-shell');
var pyshell = new PythonShell('my.py');
pyshell.on('message', function(message) {
console.log(message);
});

但是得到了错误

代码语言:javascript
运行
复制
events.js:85
throw er; // Unhandled 'error' event
Error: spawn python ENOENT
at exports._errnoException (util.js:746:11)
at Process.ChildProcess._handle.onexit (child_process.js:1046:32)
at child_process.js:1137:20
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3

附言:我已经安装了Python shell

另外,如果我想执行从node.js到python脚本的单个函数。我能做到吗?帮帮忙

EN

回答 4

Stack Overflow用户

发布于 2017-06-20 18:49:55

您可以像这样简单地编写'my.py‘文件-

代码语言:javascript
运行
复制
def printme(str):
    return str;

print(printme("I'm first call to user defined function!"));

检查给定的路径是否正确,并检查是否有缩进错误。

票数 2
EN

Stack Overflow用户

发布于 2020-01-09 15:38:31

您可以简单地使用let关键字而不是const关键字导入Npm Pythonshell。

代码语言:javascript
运行
复制
let {PythonShell} = require('python-shell')

这对我很管用

票数 1
EN

Stack Overflow用户

发布于 2015-03-01 13:51:42

您的print语句(my.py第2行)被注释掉了,因此不会输出任何内容,因此消息事件永远不会触发。取消对打印语句的注释,节点PythonShell对象将重定向标准输出(打印将写入该输出),并使用输出触发一个消息事件。

至于您的错误,看起来在当前目录中找不到python脚本。有关错误代码及其含义,请参阅https://docs.python.org/2/library/errno.html。确保您的脚本位于正确的目录中,或者使用os.chdir将python shell设置为正确的目录。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28790514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档