Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a Python script from a Node.js AWS Lambda Function

Running non Node.js executables from a Node.js Lambda Function is possible as described here.

Having a Node.js Lambda Function I want to run a Python script using Node.js' child_process command.

I followed this AWS tutorial and included the following at the start of my .js function:

process.env[‘PATH’] = process.env[‘PATH’] + ‘:’ + process.env[‘LAMBDA_TASK_ROOT’];

And the main Python script call starts here:

const { spawn } = require('child_process');

function calculateSomething(next) {
  var script = spawn('python', ['my_python_script.py', args]);

  script.stdout.on('data', (data) => { doSomething(data); });
  script.on('error', (error) => { console.error(error); });
  script.on('exit', () => { next(); });
}

The Python script runs using an external library (e.g., numpy), so I have to install it using pip.

Now:

  • What do I have to do for installing pip libraries inside a Node.js Lambda?
  • Is it enough for linking my Python script with Node.js Function to add this process.env[‘PATH’] = process.env[‘PATH’] + ‘:’ + process.env[‘LAMBDA_TASK_ROOT’]; at the start of my .js function?

It's similar to this other question.

like image 207
javiergarval Avatar asked Jan 17 '19 12:01

javiergarval


People also ask

CAN node run Python script?

This is the simple implementation of a how-to run python script with Node. js which can be useful in situations where you have a stack of Node. js application and you want to run a simple python script. If you want to know more about PythonShell module, then go through the given link.

Can I use Python packages with AWS Lambda?

Python packages that contain compiled code (for example: NumPy and pandas) aren't always compatible with Lambda runtimes by default. If you install these packages using pip, then the packages download and compile a module-name package for the architecture of the local machine.


1 Answers

You need a custom runtime to run multiple languages

like image 80
Efren Avatar answered Oct 18 '22 20:10

Efren