Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not printing output

Tags:

python

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?

like image 941
mark Avatar asked Mar 24 '19 15:03

mark


People also ask

Why is my program not printing Python?

The most usual reasons that your function does not give an printed output are: You are not telling it to: i.e. use print(fn()) rather than just fn()

How do you display output in Python?

We can use print() function in Python to display some message or output on Python shell. Here EXPRESSION is the variable of any data type or string value that we want to display.

How do I force Python to print?

flush() will force the print functions that can be print() or sys. stdout. write() to write the output on the screen or file on each call and not buffer it.

How do you print text in Python?

Print Function The Python print() function takes in any number of parameters, and prints them out on one line of text. The items are each converted to text form, separated by spaces, and there is a single '\n' at the end (the "newline" char).


1 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
like image 99
snwflk Avatar answered Oct 25 '22 07:10

snwflk