简体   繁体   English

如何从服务器端Javascript执行Python脚本

[英]How to execute a Python script from server side Javascript

There are a number of answers in relation to how one can execute a Python script from the client side. 关于如何从客户端执行Python脚本,有许多答案。 I am interested in finding out if it is possible to execute the script from the server side and check if the execution has finished successfully. 我有兴趣了解是否可以从服务器端执行脚本,并检查执行是否成功完成。 Let say that I'm using Meteor stack which uses JavaScript on both sides and there are a bunch of Python script tasks that needs to be triggered from backend. 假设我正在使用Meteor堆栈,该堆栈在两侧均使用JavaScript,并且有大量Python脚本任务需要从后端触发。

If you need python scripts at you project the most common way is to connect python and meteor through message queue. 如果您在项目中需要python脚本,则最常见的方法是通过消息队列连接python和流星。 For example on meteor occured action which should trigger some python script. 例如在流星上发生的动作应该触发一些python脚本。 You send message to queue for python. 您将消息发送到python队列。 Python listening queue and when get your message starts task. Python侦听队列以及何时获取消息启动任务。 After task is done, python should send message to queue, maybe with results of task or else. 任务完成后,python应该将消息发送到队列,可能带有任务的结果,否则。

//Meteor server side
var amqp = Meteor.require('amqp');
var connection = amqp.createConnection(amqpCredentials);
var Fiber = Npm.require("fibers");

connection.on('ready', function(){
    connection.queue(queueName, {autoDelete: false}, function(queue){

      console.log(' [*] Waiting for messages. To exit press CTRL+C')

      queue.subscribe(function(msg){
          console.log(" [x] Received %s", msg.data.toString('utf-8'));
          var msg = EJSON.parse(msg.data);
          if(msg.type === 'news'){
            Fiber(function(){News.insert(msg.data).run()});
          }
      });
  });

}); });

At the python's side you should run tasks and add listener of queue. 在python端,您应该运行任务并添加队列侦听器。 You can read about RabbitMq and python client at official documentation RabbitMQ tutor 您可以在官方文档RabbitMQ教程中阅读有关RabbitMq和python客户端的信息。

You can do it simply with a command line invokation, the same way as in any Node application: 您可以使用命令行调用简单地完成此操作,就像在任何Node应用程序中一样:

var exec = Npm.require('child_process').exec;
var Fiber = Npm.require('fibers');


new Fiber(function(){
  exec("python command", function (error, stdout, stderr) {
    ...
  });
}).run();

Meteor runs within a NodeJS container. 流星在NodeJS容器中运行。 Hence you should be able to use a package like execSync to do this task for you. 因此,您应该能够使用execSync之类的包为您完成此任务。

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

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