如何等待子进程在Node.js中完成?

时间:2014-03-11 21:51:46

标签: python node.js child-process

我正在通过Node.js中的子进程运行Python脚本,如下所示:

require('child_process').exec('python celulas.py', function (error, stdout, stderr) {
    child.stdout.pipe(process.stdout);
});

但Node不等待它完成。我怎么能等待这个过程结束?

编辑:是否可以通过在我从主脚本调用的模块中运行子进程来执行此操作?

5 个答案:

答案 0 :(得分:41)

对子进程使用exit事件。

var child = require('child_process').exec('python celulas.py')
child.stdout.pipe(process.stdout)
child.on('exit', function() {
  process.exit()
})

PS:这不是真的重复,因为你不想使用同步代码,除非你真的需要它。

答案 1 :(得分:4)

你应该使用exec-sync

允许你的脚本等待exec完成

非常好用:

var execSync = require('exec-sync');

var user = execSync('python celulas.py');

看看: https://www.npmjs.org/package/exec-sync

答案 2 :(得分:2)

You need to remove the listeners exec installs to add to the buffered stdout and stderr, even if you pass no callback it still buffers the output. Node will still exit the child process in the buffer is exceeded in this case.

var child = require('child_process').exec('python celulas.py');
child.stdout.removeAllListeners("data");
child.stderr.removeAllListeners("data");
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);

答案 3 :(得分:0)

我认为,处理此问题的最佳方法是实现事件发射器。当第一个生成完成时,发出一个事件,表明已完成。

const { spawn } = require('child_process');
const events = require('events');
const myEmitter = new events.EventEmitter();


firstSpawn = spawn('echo', ['hello']);
firstSpawn.on('exit'), (exitCode) => {
    if (parseInt(code) !== 0) {
        //Handle non-zero exit
    }
    myEmitter.emit('firstSpawn-finished');
}

myEmitter.on('firstSpawn-finished', () => {
    secondSpawn = spawn('echo', ['BYE!'])
})

答案 4 :(得分:0)

NodeJS支持同步执行此操作。 使用这个:

const exec = require("child_process").execSync;

var result = exec("python celulas.py");

// convert and show the output.
    console.log(result.toString("utf8");

请记住将缓冲区转换为字符串。否则,您将只剩下十六进制代码。