python-shell problem with sync inside javascript

Question:

I’m using python-shell to run a Python code that return some messages inside a JavaScript environment, but the messages come out of sync. The first message returns at the right moment, but then all other messages comes out together at the end, not one by one.

When I run the test.py alone the messages come in the right way, which possibly means that is not a problem with my python code. Despite all other messages is logged together, the time when they are executed inside the python code is right, what can be seeing by the time: inside each message.

But what happens in my browser environment is the message <2>FIRST TEST logged first, and then <3>TEST and <4>MORE TEST are logged together after 10 seconds.

enter image description here

This is my python code test.py:

import sys
import time
import threading

def test():
    start = time.time()
    end1 = time.time()
    print("<2>FIRST TEST time: {}".format(end1 - start))

    time.sleep(5)
    end2 = time.time()
    print("<3>TEST time: {}".format(end2 - start))

    time.sleep(5)
    end3 = time.time()
    print("<4>MORE TEST time: {}".format(end3 - start))

x = threading.Thread(target=test)
x.start()
sys.stdout.flush()

This is my JavaScript code execPyShell.ts:

const exec: () => void = () => {
    console.log('Start')
    let pyshell = new PythonShell('./engine/test.py');
    let newLogs: string[] = [];

    pyshell.on('message', function(message: string) {
        console.log(message);
    })

    pyshell.end(function (err: any) {
    if (err){
        throw err;
    };
        console.log('Finished');
    });
}
Asked By: anti-duhring

||

Answers:

Solved! I forgot that I had to add

sys.stdout.flush()

After every print() called to force it to flush the buffer.

Answered By: anti-duhring