从 child_process.spawn 检索 shell 错误输出

bra*_*ipt 3 node.js

我正在使用child_process.spawn并且需要捕获命令失败时发生的 shell 错误。根据这个问题,我应该能够做到:

var child_process = require('child_process');

var python = child_process.spawn(
    'python', ["script.py", "someParam"]
);
python.on('error', function(error) {
    console.log("Error: bad command", error);
});
Run Code Online (Sandbox Code Playgroud)

当我用 替换'python', ["script.py", "someParam"]banana,就像在链接的问题中一样,它可以工作,并且错误是可见的。但在我的情况下,使用带参数的 python,永远不会调用 'error' 事件。

如何从python捕获shell错误?

Tro*_*ott 5

根据事件的 Node.js 文档ChildProcess error,它仅在几种情况下被触发:

  1. 无法生成该进程,或
  2. 进程无法终止,或
  3. 无论出于何种原因,向子进程发送消息都失败了。

要捕获 shell 错误输出,您还可以侦听衍生进程datastdout和事件stderr

python.stdout.on('data', function(data) {
    console.log(data.toString()); 
});

python.stderr.on('data', function(data) {
    console.error(data.toString());
});
Run Code Online (Sandbox Code Playgroud)

要捕获 shell 错误代码,您可以将侦听器附加到exit事件:

python.on('exit', function(code) {
    console.log("Exited with code " + code);
});
Run Code Online (Sandbox Code Playgroud)