Python not printing output

Question:

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?.

Asked By: mark

||

Answers:

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
Answered By: snwflk
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.