【问题标题】:How to kill nodejs child processes which execute python commands including activating and deactivating venv如何杀死执行python命令的nodejs子进程,包括激活和停用venv
【发布时间】:2022-01-13 15:30:56
【问题描述】:

我是在 nodejs 中使用子进程模块的新手,在使用 python 的 virtualenv 库时卡住了

我在 expressjs api 中有一个 post 路由,用于激活 python virtualenv,在 exec() 子进程上运行 python 并停用 virtualenv。

我在项目文件夹的其中一个模块中进行了这样的设置

// importing node modules
const { exec } = require("child_process");
const kill = require("tree-kill");

在控制器函数中,我正在尝试以这种方式创建子进程

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 需要更多时间,它可能会发生冲突。

有没有更有效的方法来异步杀死它们?

【问题讨论】:

    标签: python node.js express virtualenv child-process


    【解决方案1】:

    您可以使用execSync 同步运行它们

    试试这个:

    // importing node modules
    const {execSync } = require('child_process');
    
    
    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');
          
    } catch (err) {
        // handle command_proc err
        console.log('output', err);
        console.log('sdterr', err.stderr.toString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 2022-01-16
      • 2011-02-07
      • 1970-01-01
      • 2010-12-08
      相关资源
      最近更新 更多