1

I'm trying to execute a machine learning script from a node.js application, using the child-process core module as explained here

However, I can't get a simple output from script.stdout.on.

I'm using Node v12.5.0 and python 3.7.3

I made a sample "hello world" script and JS function to test (shown below), and ran the script from command line just fine.

These are my scripts:

test.py

import sys

print('hello world')
sys.stdout.flush()

JavaScript test function

  const { spawn } = require("child_process");
  const pytest = spawn("python", ["./path/to/test.py"]);
  console.log("firstPrint");

  pytest.stdout.on("data", data => {
    console.log("secondPrint");
    console.log(data);
  });

  pytest.stdout.on("close", code => {
    console.log(`script closed: ${code}`);
  });

My console output is:

firstPrint
script closed: false

Although it should be:

firstPrint
secondPrint
hello world
script closed: {code}
J_mesh
  • 21
  • 7
  • Chances are the script errored out for some reasons (e.g., wrong PATH). I'f add an `on('close') call to `pytest` and double check the script executed properly. – Mureinik Jul 21 '19 at 09:04
  • @Mureinik the script exits, I updated the post. Thanks! – J_mesh Jul 21 '19 at 09:07
  • Add `pytest.stderr.on('data', (data) => { console.log(\`stderr: ${data}\`); });` to see if there are errors. – dfsq Jul 21 '19 at 09:09
  • @dfsq Can't open file or directory error. I tried moving the file to the same directory and using "./test.py", "/test.py" and "test.py", still can't open it. – J_mesh Jul 21 '19 at 09:13
  • Check files permissions, what uses and group owns the files? – dfsq Jul 21 '19 at 09:18
  • @dfsq attached image [here](https://imgur.com/OcmaBio) All of the users and groups listed have read and write permissions – J_mesh Jul 21 '19 at 09:26

1 Answers1

1

What ended up being the problem for me:

As suggested by @dfsq I added a pytest.stderr.on callback and received a "can't open file" error.

Node always executes the "spawn" command from the root folder of the project, so in my case I had to manually add "./src" to the path even though the script executing the "spawn" command was inside /src.

The script which executes JS function is inside /src

Old path (didn't work): "./test.py"

New path (works): "./src/test.py"

Community
  • 1
  • 1
J_mesh
  • 21
  • 7