【发布时间】:2023-03-24 22:18:01
【问题描述】:
在我的 VS Code 扩展中,我想调用一个 python 文件并将标准输出附加到 VSCode 的输出通道。我知道我可以通过vscode.window.createOutputChannel("..."); 创建一个输出通道,并且我也知道我可以通过这些 API 执行这样的 python(或者就此而言,任何本地 bash)脚本:https://nodejs.org/api/child_process.html。是否可以实时(即在脚本运行时)将标准输出信息附加到此输出通道?
我目前拥有的如下:
export function execute(cmd: string, callback: any, logging?: vscode.OutputChannel) {
const spwanedProcess = spawn(cmd, [], {shell: true, detached: true});
console.log(`spawned pid ${spwanedProcess.pid} with command ${cmd}`);
spwanedProcess.stdout.on('data', (data: any) => {
console.log(data);
logging?.appendLine("stdout:" + data);
});
spwanedProcess.stderr.on('data', (data: any) => {
console.error(`spawned pid ${spwanedProcess.pid} pushed something to stderr`);
logging?.appendLine(data);
});
spwanedProcess.on('exit', function(code: any) {
if (code !== 0) {
console.log('Failed: ' + code);
}
else {
console.log(`pid ${spwanedProcess.pid} finished`);
}
callback();
});
}
其中callback() 是执行完成后要执行的内容。我从这里得到了这个结构https://stackoverflow.com/a/32872753/14264786。
但是,当我运行一个休眠 3 秒并打印一些内容并再次执行此操作的简单 Python 代码时,标准输出信息仍未实时显示在日志记录中。相反,它们会在脚本完成后一起输出。
知道什么是潜在的解决方案吗?
【问题讨论】: