[英]Spawn child process from node to run python script returns 500
我正在尝试生成一个子进程以从 Node.js 运行 python 脚本。 我收到以下请求:
/webcrawler?source=http://www.pygamers.com&method=BFS&nodeCount=3&depth=0&keyword=game
我已验证我的参数输入正确。 这是我为处理app.js
中的请求而设置的代码:
app.get('/webcrawler', function(req, res){
var python = require('child_process').spawn(
'python',
["WebCrawler/Webcrawler.py"
, req.query.source
, req.query.method
, req.query.nodeCount
, req.query.depth
, req.query.keyword]
);
var output = "";
python.stdout.on('data', function(data){ output += data });
python.on('close', function(code){
if (code !== 0) {
return res.send(500, code);
}
return res.send(200, output);
});
});
我正在调用我的 Python 脚本Webcrawler.py
,它位于 WebCrawler 目录中。 WebCrawler 目录与app.js
位于同一目录中。
但是,这个请求给我一个 500,我一直没弄清楚为什么。 看来我一定是错误地生成了子进程。 为此,我将此答案用作 model。
它必须是绝对路径,例如/home/username/Webcrawler/webcrawler.py
听起来像是路径问题。 还要签出python-shell软件包。 使您的生活变得如此轻松。
你可以在 npm -native-python上查看这个 package
它提供了一种非常简单而强大的方法来从节点运行 python 函数可能会解决您的问题。 从'@guydev/native-python'导入{runFunction}
const example = async () => {
const input = [1,[1,2,3],{'foo':'bar'}]
const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)
// error will be null if no error occured.
if (error) {
console.log('Error: ', error)
}
else {
console.log('Success: ', data)
// prints data or null if function has no return value
}
}
python模块
# module: file.py
def hello_world(a,b,c):
print( type(a), a)
# <class 'int'>, 1
print(type(b),b)
# <class 'list'>, [1,2,3]
print(type(c),c)
# <class 'dict'>, {'foo':'bar'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.