简体   繁体   中英

Why Child Process Skipped to run my Python Script?

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

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 .

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