Skcript Technologies Private Limited

← All Articles

How to Execute Python Scripts in Electron and NodeJS

— Written by

How to Execute Python Scripts in Electron and NodeJS

With Electron it’s so easy to build cross platform desktop applications. However you might need to access functionality that isn’t readily available in JavaScript. Python to the rescue! In this article, you’ll discover how to execute Python scripts from Electron or NodeJS applications.

When developing a desktop application, some of the functionalities or packages won’t be available in Electron JS or Node JS. Sometimes with JS, you will not be able to access the full functionality of an operating system. In such cases it’s advisable to use a general purpose language.

For example, I built an application to go into “Zen Mode” on my desktop. This disables all keyboard access so that it’s easier for me to step away from the digital world. In the Electron app, I wanted to disable all keyboard and mouse inputs using JS, but it wasn’t possible. It’s only possible to control mouse inputs using the iohook package (there’s no function to disable keyboard inputs). There are no other packages available for this kind of functionality. However, we can easily do it with the help of Python packages like pyhook and pythoncom.

In this blog, we will discuss how to execute Python scripts directly from Electron JS.

Retrieve data from a Python script

First, we need to install a python-shell package which helps us to communicate with our Python script.

In your terminal, execute the following command:

npm install python-shell

After installing the python-shell package, create file script.py

import sys
print("Command executed from Python script")
sys.stdout.flush()

The above lines just imports a Python package sys and “print” basically works as a “return” statement here.

sys.stdout.flush() collects the data “written” to standard out before it writes it to the terminal.

Now let’s code our **main.JS **file.

const {PythonShell} = require('python-shell');

let pyshell = new PythonShell('script.py');

pyshell.on('message', function(message) {
  console.log(message);
})

pyshell.end(function (err) {
  if (err){
    throw err;
  };
  console.log('finished');
});

“Message” variable contains the data which is pushed by the Python script. “Pyshell.on” retrieves the written data from the python script and stores it in a message variable. “Pyshell.end” ends and exits the process.

Send data to Python script

Now that we have understood how to retrieve data from a Python script. Let’s see how to send data to the Python script.

const {PythonShell} = require('python-shell');

let pyshell = new PythonShell('script.py');

pyshell.send(JSON.stringify([10]))

pyshell.on('message', function(message) {
  console.log(message);
})

pyshell.end(function (err) {
  if (err){
    throw err;
  };
  console.log('finished');
});

In the above code, we are trying to send data in the form JSON format. We can also send data in the form of an object but the python script will read the data as a string. Hence we are sending data to the script in JSON format.

Now we need to modify our Python script a little bit.

import sys,json
data = sys.stdin.readlines()
data = json.loads(data[0])
print(data[0]+10)
sys.stdout.flush()

Since we need to parse data from JSON, we require the JSON library. Sys.stdin.readlines reads all the data which is sent to the Python shell. The Python shell sends and receives data in the form of string.

Now let’s execute the main.js file and see the output.

We can also make use of options to send data to Python script.

  let options = {
    mode: 'text',
    pythonPath: 'Your python path',
    pythonOptions: ['-u'],
    scriptPath: 'Your script path',
    args: [10]
  };

  PythonShell.run('script.py',options,function(err,results) {
    if(err) throw err;
  });

In options, we give our arguments in “args” in the form of an array. In Python script we can access args using sys.args[1]

And that’s it! You can now integrate Python scripts inside your Electron or Node JS apps.

Up next

Simple guide to work with an outsourced company to build a new product
Skcript /svr/how-to-execute-python-scripts-in-electron-and-nodejs/ /svrmedia/heroes/how-to-execute-python-scripts-in-electron-and-nodejs-1-5x.jpg
Skcript Technologies Private Limited

Book a free consultation

Book a time with our consultants to discuss your project and get a free quote. No strings attached.