How to Execute a Python Script in a Node.js Project

This tutorial assumes that you’ve already set up a basic Node.js project with Express. I have other tutorials explaining how to do this if you don’t know how.

First, create a new python file in your Node project directory. I will call mine hello.py. In hello.py, I will write a simple Python print statement to test.

print("Hello world")

In my main JavaScript file, I’m going to add the bolded line:

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

const app = express();

app.get('/', (req, res) => {
   console.log('Hello world');
});

app.listen(4000, console.log('Server started on port 4000'));

In the code above, we set up a basic Express app with one get router. Pay attention to the bolded line:

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

Next, we will use the new spawn class that we imported with this line from the child_process library.

In the get router, add the following lines:

app.get('/', (req, res) => {
   const childPython = spawn('python', ['hello.py']);

   childPython.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`)
   });

   childPython.stderr.on('data', (data) => {
      console.error(`stderr: ${data}`);
   });

   childPython.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
   });
});

In the above code, spawn a new child_process with parameters ‘python‘ and ‘script1.py‘. We set this to an object called childPython:

const childPython = spawn('python', ['hello.py']);

The first parameter is the program we want to call and the second is an array of strings that will use the python program. It is the same command if you wanted to write it in a shell to run the script1.py: python 'script1.py'

The first event is:

childPython.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`)
 });

The data argument that we are receiving from the callback function will be the output of the Python code we wrote in hello.py. We could also get access to the outputs this way. In the code below, we have to either return or console.log the dataToSend.

python.stdout.on('data', function (data) {
   dataToSend = data.toString();
});

If this event fails, the error event will be called:

childPython.stderr.on('data', (data) => { 
    console.error(`stderr: ${data}`);
});

This is the final event. The close event is emitted (run) when the stdio streams of a child process have been closed:

childPython.on('close', (code) => {
   //res.send(dataToSend)
   console.log(`child process exited with code ${code}`);
});

Here’s another example of a very basic program. This program will generate a random number between 0 and 9 (inclusive):

The contents of num.py file:

import random 

def generate():
    return random.randint(0, 9)

print(generate())

The contents of index.js file:

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

const childPython = spawn('python', ['hello.py']);

childPython.stdout.on('data', (data) => {
    console.log(`The new random number is: ${data}`)
});

childPython.stderr.on('data', (data) => {
    console.error(`There was an error: ${data}`);
});

childPython.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

const app = express();

const PORT = process.env.PORT || 4000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));

The output should look something like this:

Building a Simple Model in TensorFlow

What are we building?

We will be building a very simple TensorFlow model that adds two numbers together. This will seem trivial, but it’s an uncomplicated way to introduce yourself to TensorFlow and making models.

How to build it

  1. Open PyCharm and create a new project
  2. Save the project with a .py extension. For example, addition.py

Now, time to code.

import os
import tensorflow as tf

First, we import the things we will need into our Python project. We add the as tf when we import TensorFlow so you don’t have to type the entire name out each time you want to access it.

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

Then, we add this line to prevent TensorFlow from flooding the screen with a bunch of log messages, like it normally does. It makes the output easier to read.

X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")

Here we define the X and Y input nodes. We are defining them as placeholder nodes that will get a different value each time we run it. In the parentheses, we set their data types and give them names.

addition = tf.add(X, Y, name="addition")

This node does the actual adding. We are basically asking it to add X and Y in this line. We also must give it a name.

# create the session
with tf.Session() as session:

     result = session.run(addition, feed_dict={X: [5], Y: [3]})
     print(result)

# output: [ 8. ]

We need to create a TensorFlow session to run the addition operation on X and Y. We input values for X and Y with the feed_dict parameter.

We are feeding the model arrays because TensorFlow always works with tensors, or multi-dimensional arrays.

You can now run your code.

import os
import tensorflow as tf

# Turn off TensorFlow warning messages in program output    (limits # of log messages)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# Define the nodes
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")

addition = tf.add(X, Y, name="addition")

# Create the session
with tf.Session() as session:

    result = session.run(addition, feed_dict={X: [1, 5, 6], Y: [3, 4, 5]})

    print(result)

Since the inputs are arrays, you can put multiple numbers for X and Y. The output for the above should be [ 4. 9. 11. ]

This simple program may have seemed over-complicated just to do addition, but it taught you the basic structure of creating and running a TensorFlow model:

  1. Define a model
  2. Create a session
  3. Pass in data
  4. Send it to TensorFlow for execution

How to Install Python and PyCharm

Python is an extremely popular programming language that is commonly used in machine learning and data science. It is one of the smartest languages to learn.

PyCharm is a good IDE (Integrated Development Environment) for Python. An IDE is the software that allows you to write and test your code. There are different IDEs for different programming languages.

How to Install Python

  • Step 3: Press the big yellow download button for the latest version for your OS (It should be Python 3 or higher)
  • Step 4: Click on the downloaded file to launch the installer
  • Step 5: Set it up however you want. I suggest just choosing all of the default options by continuing to press “Continue,” but it depends on your individual situation
  • Step 6: If your on Mac, check to make sure the install was successful by opening up Terminal. Type this in:
python -v

How to Install PyCharm

  • Step 1: Go to https://www.jetbrains.com/pycharm/
  • Step 2: In the center of the screen, press the big black “Download Now” button. You should be transported to a new window that says “Download PyCharm” at the top
  • Step 3: Choose your correct OS (Windows, macOs, or Linux). Then choose the Professional (not free) or Community (free) version of PyCharm and press “Download”
  • Step 4: When the download completes, click on the file to open it
  • Step 5: Simply drag the PyCharm application to the Applications folder, as you’ve been prompted
  • Step 6: Go to your Applications folder and run PyCharm
  • Step 7: Setup PyCharm. Just press “Skip Remaining and Set Defaults” button at the bottom-left to accept the default settings

You’re all set. Now you can press “Create New Project” to get started with a new Python project