python-shell icon indicating copy to clipboard operation
python-shell copied to clipboard

Continuous data transfer from javascript to python and vice versa without ending the python process.

Open prince381 opened this issue 3 years ago • 1 comments

The Question: I have a nuxt-electron application that I want to use python as my backend. I have a python script that is supposed to run forever and continuously read data from javascript using python-shell. How can I configure python-shell to run my python script without ending the process.

My javascript code in electron's main.js

let python = new PythonShell('./python/client.py',{mode: 'text'});

ipcMain.on('send-msg',(event,data) => {
  let win = BrowserWindow.fromWebContents(event.sender);
      
  python.send(data)
  python.on('message',(msg) => {
     win.send('recv-msg',msg)
  });

  python.end(err => {
     if (err) console.log(err)
  });
})

In my python application

import sys

resp = sys.stdin.read()

while True:
    print(resp)
    resp = sys.stdin.read()

prince381 avatar Jul 26 '21 16:07 prince381

Just a guess as I haven't actually used this library yet, but it looks like you should try moving your python.end(... call to a different ipcMain listener, something like below, while leaving the rest of your code in the ipcMain.on('send-msg'... as it is.

ipcMain.on('closed', () => {
  mainWindow = null;

  python.end(err => {
    if (err) console.log(err);
  });

  if (process.platform !== 'darwin') {
    app.quit();
  }
});

f-o-w-l avatar Aug 03 '21 19:08 f-o-w-l