11

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?


This problem can also occur when trying to suppress the newline from the end of print output. See Why doesn't print output show up immediately in the terminal when there is no newline at the end?.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
mark
  • 351
  • 1
  • 3
  • 16
  • 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

14

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
  • 3,341
  • 4
  • 25
  • 37