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}
6
  • 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. Commented Jul 21, 2019 at 9:04
  • @Mureinik the script exits, I updated the post. Thanks! Commented Jul 21, 2019 at 9:07
  • Add pytest.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); to see if there are errors. Commented Jul 21, 2019 at 9: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. Commented Jul 21, 2019 at 9:13
  • Check files permissions, what uses and group owns the files? Commented Jul 21, 2019 at 9:18

1 Answer 1

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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.