Skip to content Skip to sidebar Skip to footer

Emitting Messages From Python-shell To A Browser In A Node Express App

I have an express app and I would like to be able to trigger python scripts via routes and emit the log into the browser. I have created a route which triggers the python scripts

Solution 1:

socket.io is a good solution. This will take care of passing the messages from the server to the client. You just post the message to on the server side, and have a callback react to it on the client side

On the server side you'll have something like this:

var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){ 
  console.log('connected');
});
server.listen(3000);

...

var pyshell = newPythonShell('printRange.py', options);
pyshell.on('message', function (message) {
  if (connected)
     io.emit('logentry',message);
});

On the client side, you'll have something like this:

<scriptsrc='/socket.io/socket.io.js'></script><script>var socket = io();
  socket.on('logentry',function(log_entry){
    add_to_html(log_entry); // You need to implement this function.
  });
</script>

Post a Comment for "Emitting Messages From Python-shell To A Browser In A Node Express App"