简体   繁体   English

如何在Javascript中顺序调用Python连接:Node.js

[英]How to invoke Python connection sequentially in Javascript:Node.js

I'm trying to develop a connection between node.js file and Python code which I achieved successfully using zeroRPC. 我正在尝试开发node.js文件和Python代码之间的连接,这是我使用zeroRPC成功实现的。 The problem arises when I try to run the node.js file, after executing each line of node.js file, in the end it executes the 'invoke' command that makes the python connection and calls the python function and retrieves the value.For example: 当我在执行node.js文件的每一行之后尝试运行node.js文件时,问题出现了,最后它执行了'invoke'命令,该命令生成python连接并调用python函数并检索值。例:

Node.js File: Node.js文件:

  var global_variable = 0;
  var json_object = "Some Json Object";
  console.log("1");
  NodeToPython(json_object);         //Calling the function

  function NodeToPython(json_object_local)
  {
     var send_json = json_object_local;
     var zerorpc = require("zerorpc");
     var client = new zerorpc.Client();
     client.connect("tcp://localhost:4242");

     console.log("2");
     client.invoke("receive", send_json, function(error, res, more) 
     {
       global_variable = JSON.parse(res);        // 'res' stores retrieved value from Python code
       console.log("3");
       client.close();
     }
     console.log("4");
 }
 console.log("5");

Python File: Python文件:

   import zerorpc, json
   class XYZ(object):

      def receive(self,response):                    // Called function 
          self.response=json.loads(response);
          print("Py");
          return json.dumps(self.response,encoding="utf-8",indent=2);

The output of the above code will be as follows: 1 2 4 5 Py 3 上述代码的输出如下: 1 2 4 5 Py 3

I want the output to be sequential like line by line and should simultaneously call and get the value from Python function also, like this: 1 2 Py 3 4 5 我希望输出像逐行一样顺序,并且应该同时调用并从Python函数中获取值,如下所示:1 2 Py 3 4 5

NodeJS favors continuation passing style of programming. NodeJS倾向于继续传递编程风格。 When you call invoke on the client, you are scheduling a function to run later. 在客户端上调用invoke时,您正在安排稍后运行的函数。 Whenever the RPC call succeeded or failed this function will be called with the result and possible error. 每当RPC调用成功或失败时,将使用结果和可能的错误调用此函数。 From then you can continue work and schedule more function. 从那时起,您可以继续工作并安排更多功能。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM