[英]How to kill nodejs child processes which execute python commands including activating and deactivating venv
我是在 nodejs 中使用子進程模塊的新手,並且在使用 python 的 virtualenv 庫時卡住了
我在 expressjs api 中有一個發布路由,旨在激活 python virtualenv,在 exec() 子進程上運行 python 並停用 virtualenv。
我在項目文件夾中的一個模塊中進行了這樣的設置
// importing node modules
const { exec } = require("child_process");
const kill = require("tree-kill");
在 controller function 中,我正在嘗試以這種方式創建子進程
let activate_proc = exec("source pyenv/bin/activate");
let command_proc = exec("python insert.py arg1 arg2", (error, stdout, stderr) => {
// handle status/messages with http codes
});
let deactivate_proc = exec("deactivate");
我能夠捕獲這些進程的 pid,並嘗試通過暫停 10 秒來使用 tree-kill 殺死
setTimeout(() => {
kill(command_proc.pid);
kill(activate_proc.pid);
kill(deactivate_proc.pid);
console.log("Killed all processes");
}, 10000)
這似乎有效,但不知何故,如果 command_proc 需要更多時間,它可能會發生沖突。
有沒有更有效的方法來異步殺死它們?
您可以使用execSync同步運行它們
嘗試這個:
// importing node modules
const {execSync } = require('child_process');
const kill = require('tree-kill');
let activate_proc = execSync('source pyenv/bin/activate');
let command_proc;
let deactivate_proc;
// use try/catch for stderr
try {
command_proc = execSync('python insert.py arg1 arg2');
// stdout buffer, turn it to string
const result = command_proc.toString();
console.log('command_proc result: ', result);
// handle status/messages with http codes
// ... process command_proc
// finish
deactivate_proc = execSync('deactivate');
kill(command_proc.pid);
kill(activate_proc.pid);
kill(deactivate_proc.pid);
} catch (err) {
// handle command_proc err
console.log('output', err);
console.log('sdterr', err.stderr.toString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.