How to execute a Python script from server side Javascript

你。 提交于 2019-12-22 18:13:15

问题


There are a number of answers in relation to how one can execute a Python script from the client side. 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.


回答1:


If you need python scripts at you project the most common way is to connect python and meteor through message queue. For example on meteor occured action which should trigger some python script. You send message to queue for python. Python listening queue and when get your message starts task. After task is done, python should send message to queue, maybe with results of task or else.

//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. You can read about RabbitMq and python client at official documentation RabbitMQ tutor




回答2:


You can do it simply with a command line invokation, the same way as in any Node application:

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


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



回答3:


Meteor runs within a NodeJS container. Hence you should be able to use a package like execSync to do this task for you.



来源:https://stackoverflow.com/questions/18508769/how-to-execute-a-python-script-from-server-side-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!