简体   繁体   中英

Executing a python script from NodeJS

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}

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM