我如何在 运行 python 代码和 nodejs 之间进行通信

How can I communicate between running python code and nodejs

我想要一些 python 代码 运行 并与 nodejs express 服务器通信。到目前为止,我可以让我的 nodejs 服务器通过两种机制之一调用 python 函数,或者生成一个 python 任务,或者让它与 zerorpc python 服务器通信。

对于第一个,la http://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/,这个有效:

var express = require( "express" );
var http = require( "http" );
var app = express();
var server = http.createServer( app ).listen( 3000 );
var io = require( "socket.io" )( server );

app.use( express.static( "./public" ) );

io.on( "connection", function( socket ) {

    // Repeat interval is in milliseconds
    setInterval( function() {

        var spawn = require( 'child_process' ).spawn,
        py    = spawn( 'python', [ 'mytime.py' ] ),
        message = '';

        py.stdout.on( 'data', function( data ) {
            message += data.toString();
        });

        py.stdout.on( 'end', function() {
            socket.emit( "message", message );
        });

    }, 50 );
});

其中mytime.py是

from datetime import datetime
import sys

def main():
    now = datetime.now()
    sys.stdout.write( now.strftime( "%-d %b %Y %H:%M:%S.%f" ) )

并且使用 zerorpc http://www.zerorpc.io/,如果这个 python 代码是 运行:

from datetime import datetime
import sys
import zerorpc

class MyTime( object ):
    def gettime( self ):
        now = datetime.now()
        return now.strftime( "%-d %b %Y %H:%M:%S.%f" )

s = zerorpc.Server( MyTime() )
s.bind( "tcp://0.0.0.0:4242" )
s.run()

此 nodejs 代码有效:

var express = require( "express" );
var http = require( "http" );
var app = express();
var server = http.createServer( app ).listen( 3000 );
var io = require( "socket.io" )( server );
var zerorpc = require( "zerorpc" );
var client = new zerorpc.Client();
client.connect( "tcp://127.0.0.1:4242" );

app.use( express.static( "./public" ) );

io.on( "connection", function( socket ) {

    // Repeat interval is in milliseconds
    setInterval( function() {

        client.invoke( "gettime", function( error, res, more ) {
            socket.emit( "message", res.toString( 'utf8' ) );
        } );

    }, 50 );
});

但我希望能够做的是不只是调用 python 函数,我想要一个单独的 python 进程 运行 并将消息发送到监听它们然后处理它们的nodejs服务器。我已经尝试过使用中间件 socketio-wildcard,但是如果我尝试在与 nodejs express 服务器相同的端口上使用 zerorpc 设置 python 服务器,它会给出 zmq.error.ZMQError:地址已在使用 错误。

我知道我没有在考虑这个问题——我知道由于我的天真,我错过了一些关于进程间通信的逻辑——所以如果有更好的方法从python 有一个 nodejs 服务器监听的进程,我洗耳恭听。

有什么想法吗?

非常感谢!

对于那些试图解决这个问题的人,这里有一个解决方案感谢 Zeke Alexandre Nierenberg

对于 node.js 服务器代码:

var express = require( "express" );
var app = express();
var http = require( "http" );
app.use( express.static( "./public" ) ); // where the web page code goes
var 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 );
    });
});

和向其发送消息的 python 代码:

from datetime import datetime
from socketIO_client import SocketIO, LoggingNamespace
import sys

while 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 )

瞧!

我在使用 socketIO 版本时遇到了一些问题...

所以,这是我的解决方案:

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...');
     });

在 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)