我的Nodejs服务器和python脚本通过socket.io组合在一起
我可以运行我的python脚本并调用它的函数,直到发送正确的数据为止
问题是当python函数出错时,我无法在NodeJS中处理它们 我想在python脚本崩溃之前了解一下,我没有运行它们 我希望你能流利地解释这个问题
JS
function startScripts() {
let child = spawn('python', ['-u', __dirname + '/pyScripts/' + 'config.py']);
sockets.on('connection', function (socket) {
socket.join('config');
socks = socket;
});
child.stderr.on('data', function (err) {
console.log(err.toString());
});
child.stdout.on('data', function (data) {
console.log(data.toString());
});
}
function runPyFunction(data, callback) {
sockets.to('config').emit('run', data);
const handleResponse = (res) => {
if (res) {
return callback({ 'message': res, 'status': 'ok' }, null);
}
else {
return callback(null, { 'message': 'Function or file is not found', 'status': 'failed' });
}
};
socks.removeAllListeners();
socks.on('response', handleResponse);
}
app.post('/py', (req, res) => {
let data = req.body;
let userData = {
'filename': 'test',
'function': 'multiplication',
'args':[3]
}
runPyFunction(userData, (res2, err) => {
if (res) {
console.log('here is message');
console.log(res);
res.end(JSON.stringify(res2))
} else {
console.log('here is error');
console.log(err);
}
})
})
PythonConfig.py
def run_function(data):
for module in globals():
if data['filename'] == module:
for function in getmembers(globals()[module], isfunction):
if data['function'] == function[0]:
print(data)
if 'args' in data:
return sio.emit('response', function[1](*data['args']))
else:
return sio.emit('response', function[1]())
# Emit false if function or file not found
return sio.emit('response', False)
test.py
import os
def multiplication(number):
return number*number*number
问题是:当python脚本死亡或崩溃时,如何处理错误
在上面的代码中,我在NodeJS和py scipts之间进行了通信 我添加了一个API'/py',我向它发送数据(这里是模拟数据),我告诉它我想用这些参数执行这个File.py和这个函数名
它搜索以找到确切的函数。 它工作得很好;例如,在上面的代码中,当我发送字符串数据时,我必须将int变量赋给py函数,我无法使用节点js中的控制器处理它
如何理解节点js中的py错误
目前没有回答
相关问题 更多 >
编程相关推荐