Call Python Code from Node.js
//Use of var here to avoid having to reload the Jupyter Notebook on every run of a cell.
var fs = require('fs');
//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.¶
fs.writeFileSync('main.py', pythonCode)
Load the PyNode library.¶
var pynode = require('@fridgerator/pynode')
// optionally pass a path to use as Python module search path
pynode.startInterpreter()
// add current path as Python module search path, so it finds our app.py
pynode.appendSysPath('./')
// open the python file (module)
pynode.openFile('main')
// 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
})
// 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
})