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

2024-05-16 02:08:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

首先,a 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" ) )

如果使用zerorpchttp://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服务器,nodejs服务器监听并处理这些消息。我已经尝试了中间件socketio通配符,但是如果我尝试在nodejs express服务器的同一端口上设置一个带有zerorpc的python服务器,它会给出一个zmq.error.ZMQError:Address already in use错误。

我知道我没有考虑好这一点——我知道由于我的天真,我在进程间通信方面缺少了一些逻辑——所以如果有更好的方法在nodejs服务器监听的情况下从python进程发送消息,我洗耳恭听。

有什么想法吗?

多谢提前!


Tags: pyio服务器apphttpmessagedatetimevar
2条回答

对于那些试图解决这个问题的人,这里有一个解决方案,感谢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版本有一些问题。。。

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

节点:

   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)

相关问题 更多 >