'Sharing memory between Python shells run by Electron

I'm currently working on a desktop application that makes use of React for frontend and runs through an electron window. Electron needs to be able to communicate with my Python backend. I've found an example online that works fine for running a simple Python script from Electron and returning the result to React.

Electron code that waits for signal from React:

ipcMain.on("REACT_TEST_PYTHON", (event, args) => {
  let pyshell = new PythonShell(
    path.join(__dirname, "../background/python/test.py"),
    {
      args: [args.test],
    }
  );
  pyshell.on("message", function (results) {
    mainWindow.webContents.send("ELECTRON_TESTED_PYTHON", { tasks: results });
  });
})

test.py that is being run by electron:

import sys

data = sys.argv[1]

def factorial(x):
    if x == 1 :
        return 1
    else:
        return x * factorial(x-1)

print(factorial( int(data) ))

I completely understand how this works, but for my application the python scripts will not be as simple. Basically, I want electron to create a Python shell that starts a named task. This Python shell should continue running in the background while the frontend works normally. The part I'm stuck on is figuring out how to access data from this initial python shell from a different python shell created by a subsequent signal in electron. If that doesn't make sense this is my intended pipeline:

  1. User clicks React button to start "Task1"
  2. Electron gets signal from React and starts a Python shell to start "Task1". This python shell is running in the background (Electron should not wait for a result to continue processing).
  3. Later on, user decides to click React button to cancel "Task1"
  4. Electron gets signal from React and creates a new Python shell to cancel "Task1". In order to do this the new Python shell needs to access data from the original Python shell.
  5. This new Python shell should also close the original Python shell so that it doesn't continue to try and run "Task1"

What would be the best way to do this?

Some thoughts I've had on how to do this:

  • Creating a file where necessary data for "Task1" could be written. I think I would need the mmap module in order to use some kind of shared memory between the shells (but I could be wrong). Would also need to figure out how to close the original Python shell.
  • Somehow saving a reference to the original Python shell which could allow for Electron to cancel "Task1" using the original shell. Not sure if this is possible though since the original Python shell will still be running, I doubt I could access the shell while its in the middle of processing.

Thank you for any help or insight you can provide! I apologize that this may be a confusing question, please let me know if I can clear anything up.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source