9

I am learning to use electron js with python and I am using python-shell so I have the following simple python script:

import sys, json

# simple JSON echo script
for line in sys.stdin:
    print(json.dumps(json.loads(line)))

and in my main.js:

let {PythonShell} = require('python-shell')
let pyshell = new PythonShell('/home/bassel/electron_app/pyapp/name.py', {mode : 'json'});
pyshell.send({name:"mark"})


pyshell.on('message', function (message) {
    // received a message sent from the Python script (a simple "print" statement)
    console.log("hi");
});

but the hi is not getting printed, what is wrong?

snwflk
  • 2,931
  • 4
  • 21
  • 34
mark
  • 331
  • 1
  • 3
  • 13
  • Does this answer your question? [Print statements not working when serve\_forever() is called?](https://stackoverflow.com/questions/43197518/print-statements-not-working-when-serve-forever-is-called) – lmat - Reinstate Monica Feb 14 '20 at 19:12

1 Answers1

13

Output is often buffered in order to preserve system resources. This means that in this case, the system holds back the Python output until there's enough to release together.

To overcome this, you can explicitly "flush" the output:

import sys, json

# simple JSON echo script
for line in sys.stdin:
    print(json.dumps(json.loads(line)))
    sys.stdout.flush()                      # <--- added line to flush output

If you're using Python 3.3 or higher, you may alternatively use:

import sys, json

# simple JSON echo script
for line in sys.stdin:
    print(json.dumps(json.loads(line)), flush=True)   # <--- added keyword
snwflk
  • 2,931
  • 4
  • 21
  • 34