杀死 process.exec 函数

Kill process.exec function

我有一个函数来执行一个进程:

static async runTest() { await process.exec(`start ${currentDir}/forward.py`); }

runTest();

python 脚本将继续 运行 直到它被杀死,我现在不知道该怎么做。所以简而言之,我想在某个时候手动终止这个进程。我该怎么做?谢谢!

exec return 值是一个子进程对象,您可以通过调用 .kill() 函数随时终止它。更多信息,您可以参考这篇

https://nodejs.org/api/child_process.html

我使用简单的超时演示了 kill 函数。

const { exec } = require('child_process');
    
    let childprocess = exec('python a.py', (error, stdout, stderr) => {
        if (error) {
            console.error(`error: ${error.message}`);
            return;
        }
    
        if (stderr) {
            console.error(`stderr: ${stderr}`);
            return;
        }
    
        console.log(`stdout:\n${stdout}`);
    });
    
    setTimeout(() => {  //Example killing
        childprocess.kill() 
    }, 2000);