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:
After installing the python-shell package, create file script.py
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.
“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.
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.
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.
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.