简体   繁体   中英

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. 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.

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

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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