我正在通过Node.js的子进程运行一个Python脚本,代码如下:
require('child_process').exec('python celulas.py', function (error, stdout, stderr) {
child.stdout.pipe(process.stdout);
});
但是 Node 不会等待它完成。我该如何等待进程完成?
通过在主脚本调用的模块中运行子进程,是否有可能实现这一点?
我正在通过Node.js的子进程运行一个Python脚本,代码如下:
require('child_process').exec('python celulas.py', function (error, stdout, stderr) {
child.stdout.pipe(process.stdout);
});
但是 Node 不会等待它完成。我该如何等待进程完成?
通过在主脚本调用的模块中运行子进程,是否有可能实现这一点?
使用exit
事件来处理子进程。
var child = require('child_process').exec('python celulas.py')
child.stdout.pipe(process.stdout)
child.on('exit', function() {
process.exit()
})
PS: 这并不是重复的问题,因为你只有在确实需要时才想要使用同步代码。
'end'
事件,可能为不同调用(exec()
、spawn()
…)发出不同的事件。 - CodeManXNodeJS支持同步地执行此操作。
使用以下代码:
const execSync = require("child_process").execSync;
const result = execSync("python celulas.py");
// convert and show the output.
console.log(result.toString("utf8"));
记得将缓冲区转换为字符串。否则你将只得到十六进制代码。
在Node.js中等待进程结束的简单方法是:
const child = require('child_process').exec('python celulas.py')
await new Promise( (resolve) => {
child.on('close', resolve)
})
您应该使用exec-sync
这可以让您的脚本等待执行完成
非常易于使用:
var execSync = require('exec-sync');
var user = execSync('python celulas.py');
在我看来,处理这个问题的最佳方式是实现事件发射器。当第一个生成进程完成时,发出一个事件表示它已经完成。
const { spawn } = require('child_process');
const events = require('events');
const myEmitter = new events.EventEmitter();
firstSpawn = spawn('echo', ['hello']);
firstSpawn.on('exit', (exitCode) => {
if (parseInt(exitCode) !== 0) {
//Handle non-zero exit
}
myEmitter.emit('firstSpawn-finished');
}
myEmitter.on('firstSpawn-finished', () => {
secondSpawn = spawn('echo', ['BYE!'])
})
即使您没有传递回调函数,您仍需要删除监听器以将安装添加到缓冲的标准输出和标准错误输出中,因为它仍会缓冲输出。在这种情况下,如果缓冲区已满,则Node仍将退出子进程。
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);
Util.promisify
,例如:const { exec } = require('child_process');
const Util = require('util');
const asyncExec = Util.promisify(exec);
asyncExec('python celulas.py')
.then((stdout, stderr) => {
stdout.pipe(process.stdout);
})
.catch(error => {
console.log('error : ', error);
});