简体   繁体   English

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

[英]How can I communicate between running python code and nodejs

I'd like to have some python code running and communicating with a nodejs express server. 我想运行一些python代码并与nodejs express服务器通信。 So far, I can get my nodejs server to call python functions via one of two mechanisms, either to spawn a python task or to have it talk to a zerorpc python server. 到目前为止,我可以让我的nodejs服务器通过两种机制之一来调用python函数,要么生成python任务,要么让它与zerorpc python服务器通信。

For the first, a la http://www.sohamkamani.com/blog/2015/08/21/python-nodejs-comm/ , this works: 第一个是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 );
});

Where mytime.py is 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" ) )

And with zerorpc http://www.zerorpc.io/ , if this python code is running: 并使用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()

This nodejs code works: 这个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 );
});

But what I'd like to be able to do is instead of just having python functions called, I'd like a separate python process running and sending messages to the nodejs server which listens for them and then handles them. 但我想要做的不是只调用python函数,我想要一个单独的python进程运行并向nodejs服务器发送消息,该服务器侦听它们然后处理它们。 I've experimented with middleware socketio-wildcard, but if I try to set up a python server with zerorpc on the same port as the nodejs express server, it gives a zmq.error.ZMQError: Address already in use error. 我已经尝试过中间件socketio-wildcard,但是如果我尝试在与nodejs express服务器相同的端口上设置一个zerorpc的python服务器,它会给出一个zmq.error.ZMQError:地址已经在使用中

I know that I'm not thinking about this right--I know that I'm missing some logic around interprocess communication due to my naïveté here--so if there is a better way to do message sending from a python process with a nodejs server listening, I'm all ears. 我知道我没有考虑到这一点 - 我知道由于我在这里的天真,我错过了一些关于进程间通信的逻辑 - 所以如果有更好的方法从一个带有nodejs的python进程发送消息服务器听,我都是耳朵。

Any ideas? 有任何想法吗?

Many thanks in advance! 提前谢谢了!

For those trying to figure this out, here's a solution thanks to Zeke Alexandre Nierenberg 对于那些想要解决这个问题的人来说,这是Zeke Alexandre Nierenberg的解决方案

For the node.js server code: 对于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 );
    });
});

and the python code that sends it messages: 以及发送消息的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 )

Voilà! 瞧!

I had some problems with socketIO version... 我在socketIO版本上遇到了一些问题......

so, this is my Solution: 所以,这是我的解决方案:

NodeJS: 的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: 在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何与 Python 中已经运行的 Linux 进程通信? - How can I communicate with an already running Linux process in Python? 如何在两个 python 脚本之间进行通信? - How can I communicate between two python scripts? 我如何在 kivy python 中的不同布局类之间进行通信 - How can i communicate between diffrent layout classes in kivy python 如何在西门子 S7-1200 和 python 之间进行通信? - How can I communicate between a Siemens S7-1200 and python? 当我在 nodeJS 中将代码作为 python shell 运行时,如何永久安装 python 包? - How can I install python packages permanently when I am running my code as a python shell in nodeJS? 如何在 NodeJS 和 Python (pynput) 之间与子进程通信 - How to communicate between NodeJS and Python (pynput) with child process 通过Websockets在Nodejs和Python之间进行通信 - Communicate Between Nodejs and Python via Websockets 如何与后台Python实例进行通信? - How can I communicate with a backgrounded Python instance? 如何使用 Python 与 Websocket 通信 - How can I communicate with the Websocket using Python 我可以使用python静态变量在两个模块之间进行通信吗? - Can I use python static variables to communicate between two modules?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM