1

I tried a fairly simple script.

import time
print("Hello World")
time.sleep(5)

This program does exactly what it appears to be doing. It prints Hello World, waits for five seconds and then exits.

However, things start getting weird when i invoked this with node.

 const spawn = require('child_process').spawn;
 const process = spawn ('python3', ['./testIn.py']);

 process.stdout.on('data', data => {
    console.log(data.toString());
 });

 process.on('close', code => {
     console.log(`child process close all stdio with code ${code}`);
 });

What happens now is that the program waits for five seconds, then prints Hello World and then exits immediately after the print. It's like the order of the two commands is reversed, first it runs the sleep() and the the print().

Does anyone have a clue on why this weird behaviour occurs?

user1584421
  • 3,499
  • 11
  • 46
  • 86
  • [Not receiving stdout from nodejs spawned process](https://stackoverflow.com/a/32636139) – 001 Sep 08 '20 at 14:09
  • Tried const process = spawn ('unbuffered', 'python3', ['./testIn.py']); but didn't work. Also tried const process = spawn ('python3 -u', ['./testIn.py']); but didn't work. – user1584421 Sep 08 '20 at 14:36
  • This works as expected on my Windows machine: `const process = spawn ('py', ['-u', 'testIn.py'], {shell: true});` – 001 Sep 08 '20 at 15:28
  • Thank you! it worked. It's all about the -u flag after all, but i was declaring it erroneously. If you would like, you can post it as a normal answer, so i can vote up and mark it as the selected answer. – user1584421 Sep 09 '20 at 08:10

1 Answers1

2

Python is buffering the output so you are not seeing it until the process ends. You can use the -u option to tell Python not to do that. From the docs, the -u option will:

Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.
Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.

However, I am running 3.7.2 on Windows 10 and could not get your code to work without the -u option.

const process = spawn ('py', ['-u', 'testIn.py']);
001
  • 13,291
  • 5
  • 35
  • 66