ways to build a desktop app with electron and python

Adarsha Regmi
2 min readMar 31, 2022

--

going into new stack is always interesting.

my_info: I have python background but no experience working in js .

Steps 1: install react and python (basic and first step to each beginning)

npm install **and python install **

step 2 : Challenge for me how to communicate python and electron

from the research, I have done

i. IPC (based upon wikipedia)

In computer science, inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow the processes to manage shared data. Typically, applications can use IPC, categorized as clients and servers, where the client requests data and the server responds to client requests.[1] Many applications are both clients and servers, as commonly seen in distributed computing. 
source: : https://en.wikipedia.org/wiki/Inter-process_communication

in short: mechanism to make communications between the processes via os.

Some of the approaches that works for us. >>

a) Node allows the user to spawn the child process.

function sendToPython() {
var python = require('child_process').spawn('python', ['./py/calc.py', input.value]);
python.stdout.on('data', function (data) {
console.log("Python response: ", data.toString('utf8'));
result.textContent = data.toString('utf8');
});

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

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

}

btn.addEventListener('click', () => {
sendToPython();
});

btn.dispatchEvent(new Event('click'));

b) using python-shell

python-shell is an npm package that provides an easy way to run Python scripts from Node.js with basic and efficient inter-process communication and error handling.

You can use python-shell for:

  • Spawning Python scripts,
  • Switching between text, JSON and binary modes,
  • Doing data transfers through stdin and stdout streams,
  • Getting stack traces in case of errors.
function sendToPython() {
var { PythonShell } = require('python-shell');

let options = {
mode: 'text',
args: [input.value]
};

PythonShell.run('./py/calc.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: ', results);
result.textContent = results[0];
});

}

c) most common approach that works

using Client-Server Communication

create a server such as fastapi, flask, sanic and api

import sys
from flask import Flask
from flask_cors import cross_origin
from calculator.simple import SimpleCalculator

def calcOp(text):
"""based on the input text, return the operation result"""
try:
c = SimpleCalculator()
c.run(text)
return c.log[-1]
except Exception as e:
print(e)
return 0.0

app = Flask(__name__)

@app.route("/<input>")
@cross_origin()
def calc(input):
return calcOp(input)

if __name__ == "__main__":
app.run(host='127.0.0.1', port=5001)

fetching in js

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

let options = {
mode: 'text'
};

PythonShell.run('./py/server.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('response: ', results);

});
}

function onclick(){

fetch(`http://127.0.0.1:5001/${input.value}`).then((data)=>{
return data.text();

}).then((text)=>{
console.log("data: ", text);
result.textContent = text;
}).catch(e=>{
console.log(e);
})

}
sendToPython();

btn.addEventListener('click', () => {
onclick();
});

btn.dispatchEvent(new Event('click'))

This seems a hint for how we can process the communication. If you want to know how I build and problems I faced. I will update this page moving forward.

A simple express framework where you can run a python script .

Github link for example

--

--