How can I communicate between running python code and nodejs How can I communicate between running python code and nodejs python python

How can I communicate between running python code and nodejs


For those trying to figure this out, here's a solution thanks to Zeke Alexandre Nierenberg

For the node.js server code:

var express = require( "express" );var app = express();var http = require( "http" );app.use( express.static( "./public" ) ); // where the web page code goesvar http_server = http.createServer( app ).listen( 3000 );var http_io = require( "socket.io" )( http_server );http_io.on( "connection", function( httpsocket ) {    httpsocket.on( 'python-message', function( fromPython ) {        httpsocket.broadcast.emit( 'message', fromPython );    });});

and the python code that sends it messages:

from datetime import datetimefrom socketIO_client import SocketIO, LoggingNamespaceimport syswhile True:    with SocketIO( 'localhost', 3000, LoggingNamespace ) as socketIO:        now = datetime.now()        socketIO.emit( 'python-message', now.strftime( "%-d %b %Y %H:%M:%S.%f" ) )        socketIO.wait( seconds=1 )

VoilĂ !


I had some problems with socketIO version...

so, this is my Solution:

NodeJS:

   var app = require("express")();   var http = require('http').Server(app);   var bodyParser = require('body-parser');    app.use(bodyParser.json())    app.post('/',function(req,res){            var msg=req.body.msg;            console.log("python: " + msg);    });     http.listen(3000, function(){     console.log('listening...');     });

on Python:

  import requests  import json  url = "http://localhost:3000"  data = {'msg': 'Hi!!!'}  headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}  r = requests.post(url, data=json.dumps(data), headers=headers)