0

I have this js code:

const python = spawn('python', [path.join(settings.PROJECT_DIR, '/tests_explorer/scripts/product/product.py').replace(/\\/g, "/"), 'node.js', 'python']);

python.stdout.on('data', function (data) {
  console.log('Pipe data from python script ...');
  dataToSend = data.toString();
  console.log(dataToSend)
 });

It should execute my python Script product.py:

import sys
import general.general //my own utils
print('#Hello from python#')
print('First param:'+sys.argv[1]+'#')
print('Second param:'+sys.argv[2]+'#')
name = general.id_generator(9)
print(name)

But the node js seems skipped to run my python, if I don't import general.general which is my own utils to generate random name, the python well executed and I can see the print data Is anyone know how to solve this? Thankyou

Josh Parinussa
  • 633
  • 2
  • 11
  • 28
  • Does this answer your question? [How to wait for a child process to finish in Node.js?](https://stackoverflow.com/questions/22337446/how-to-wait-for-a-child-process-to-finish-in-node-js) – Peter Badida Sep 26 '21 at 11:19

1 Answers1

0

Check if it's present on the path (process.env.PATH), if python even exists on your system (it may be python3 or python2) and if the path to the file is correct and perhaps not OS dependent:

const { spawn } = require('child_process');
const py = spawn('python3', ['-c', 'print("hello")']);
py.stdout.on('data', (data) => {console.log(`stdout: ${data}`);});

It works in CLI / REPL because it keeps the process open. However, in a file, it doesn't, therefore the event-based programming doesn't receive the event before the event loop manages to shutdown (kind of like while (true) {} in the background with consistent interrupts so your code can execute in-between).

For that you can utilize spawnSync() which will block the program until the process is spawned, data interchanged and process closed.

const { spawnSync } = require('child_process');
const py = spawnSync('python3', ['main.py']);
console.log(py.output.toString());

Or like in the linked question, setTimeout() or other system hacks to basically wait for the event loop to process your event (in this case on("data", ...) due to the async nature of the child_process module.

Peter Badida
  • 11,310
  • 10
  • 44
  • 90