Call Python Code from Node.js

Interpret Python Code from Node.js with npm package PyNode.

Resources

In [15]:
//Use of var here to avoid having to reload the Jupyter Notebook on every run of a cell.
var fs = require('fs');
In [16]:
//Python code
var pythonCode = `
from string import ascii_uppercase

def add(x, y):
    return x + y

def uppercase():
    return list(ascii_uppercase)

`

Write the Python code into a file inside the working directory.

In [17]:
fs.writeFileSync('main.py', pythonCode)

Load the PyNode library.

In [18]:
var pynode = require('@fridgerator/pynode')
In [19]:
// optionally pass a path to use as Python module search path
pynode.startInterpreter()
In [20]:
// add current path as Python module search path, so it finds our app.py
pynode.appendSysPath('./')
In [21]:
// open the python file (module)
pynode.openFile('main')
In [22]:
// call the python function and get a return value
pynode.call('add', 1, 2, (err, result) => {
  if (err) return console.log('error : ', err)
  console.log({result: result === 3}); // true
})
{ result: true }
In [23]:
// call the python function and get a return value
pynode.call('uppercase', (err, result) => {
  if (err) return console.log('error : ', err)
  const uppercase = String.fromCharCode(...[...Array(26).keys()].map(i => i + 0b01000001));
  console.table(uppercase);
  console.log({result: result.every((letter, i) => letter === uppercase[i])}); //true
})
ABCDEFGHIJKLMNOPQRSTUVWXYZ
{ result: true }