0

I am developing an electronjs application which needs to call a python code. I need to read the output of each iteration of a loop in Python and display it in Electron. How can I do this?

I have tried the child_process way but that only prints the output when the whole script has ended. I some thing to be displayed at the end of each iteration in the python script.

Example:

Python:

for i in range(5):
    print(i)

Electron: --some script--

python_process.on('stdout', function(data_returned){
console.log(data_returned);
console.log('aaa');
});

Desired Output: 1

aaa

2

aaa

3

aaa

4

aaa

5

aaa

daas-shukla
  • 171
  • 1
  • 2
  • 7

1 Answers1

1

Similar to this answer, you may want to flush output so that your data isn't lingering in some buffer:

for i in range(5):
    print(i, flush=True)

However, for the toy example you gave, this doesn't make a difference in my tests as the 5 values are printed in rapid succession anyway. In this example, even with flushing, all values are turned over in one go.

If your actual data is generated at a lower rate, explicit flushing may already be your solution. The following example results in separate read events for me:

import time
for i in range(5):
    print(i, flush=True)
    time.sleep(1)

If in your actual use case it may still happen that two "messages" are turned over in the same event and you definitely want to process them separately, then you simply need to split the output (e.g. line by line) and process each message separately.

This requires your output to be splittable. In the toy example, each number is printed on a separate line and you can then call splitlines, giving you a list of the lines.

How you implement this depends very much on the actual output of your Python program.


Here's the Node.js code that I used for testing. It calls the Python interpreter with script.py (this is where the above code samples would go). The Javascript code outputs stdout data and keeps track of the total number of data events.

const { spawn } = require('child_process')
const myproc = spawn('python', ['script.py'])

let counter = 0

myproc.stdout.on('data', data => {
    console.log(`stdout: ${data}`)
    counter++
})

myproc.on('close', () => {
    console.log(`child process exited after ${counter} read(s)`)
})
snwflk
  • 3,341
  • 4
  • 25
  • 37
  • i used socket.io to emit response from python script and read it at the electron end – daas-shukla Jun 14 '19 at 07:05
  • Does this change the question or invalidate the answer? Consider adding these relevant information to the question or ask a new question. – snwflk Jun 14 '19 at 13:37