I have NodeJS code like the following:
[myFile.js]
var path = require("path");
var cp = require("child_process");
var child = cp.spawn( "python",["HelloWorld.py"], { stdio:'pipe', });
child.stdout.on('data', (data) => {
console.log(`CHILD stdout: ${data }`);
});
child.stderr.on('data', (data) => {
console.log(`CHILD stderr: ${data}`);
});
process.on("SIGINT",()=>{
// close gracefully
console.log("Received SIGINT");
})
child.on('exit',(code)=>{console.log(`child Process exited with code ${code}`)})
并且像Python脚本这样:
[HelloWorld.py]
print 'Hi there'
import time
time.sleep(5)
我希望能够优雅地管理关机,但是当我通过命令行启动这段代码时:
> node myFile.js
当我按下control-C时,这个被打印到控制台上:
^CReceived SIGINT
CHILD stdout: Hi there
CHILD stderr: Traceback (most recent call last):
File "HelloWorld.py", line 3, in <module>
time.sleep(5)
KeyboardInterrupt
child Process exited with code 1
这段文本表明Python(在子进程中运行)接收了“^C”键盘事件。但是,我更喜欢子进程比在键盘中断时崩溃更加优雅地退出。
我尝试了各种组合 options.stdio 的设置,包括 [undefined,'pipe','pipe']
(不起作用),['ignore','pipe','pipe']
(导致子进程崩溃),而且我试过使用 worker.stdin.end()
(也导致子进程崩溃)。
有没有办法不继承父NodeJS进程的标准输入?
try
catch
语句中以消除错误。参见:https://dev59.com/cmw05IYBdhLWcg3wuUAL - Mike