如何使用终端API在vscode中监听所有终端输出?

8

我想要监听扩展程序的终端输出,例如 tsc -w 并在输出中捕获包含类似文本的时刻:

发现1个错误。正在监视文件更改。

或者类似错误的退出代码之类的。是否可以使用旧 API 或建议的 API 进行操作?

已尝试:

terminal.onDidWriteData(data => {
    console.log('onDidWriteData: ', data.trim());
});

它只会输出自动生成的垃圾,例如:

Windows PowerShell 版权所有 (C) Microsoft Corporation。保留所有权利。

3个回答

3
很遗憾,没有办法。有一个事件API - window.onDidWriteTerminalData,但它是一个“拟议”的API,这意味着它只在VSCode的Insiders版本中存在,您不能在发布的扩展中使用它。基本上你不能用它。
根据这个评论这个评论,尽管它是“拟议”的,但由于性能问题,它永远不会稳定下来。
作为替代方案,也许您可以将tsc -w通过另一个程序进行管道传输,该程序转发stdout/stderr并侦听触发字符串。当它看到它时,它可以通过其他方式通知您的扩展,例如编写一个您监视的文件或一些IPC系统。

不幸的是,这种方法的缺点是你不能再将终端与VSCode实例关联起来,因此如果你有多个VSCode实例运行,则可能无法正常工作。


1
看起来在Insiders版本中已经废弃了。请尝试使用window.onDidWriteTerminalData代替。"Original Answer"的翻译是"最初的回答"。
window.onDidWriteTerminalData(event => console.log(event.data.trim()))

Reference


0
为了性能原因,API: onDidWriteTerminalData event #78502已被Expose shell integration command knowledge to extensions #145234所取代,最新的API草案在this comment中。引用如下:
declare module 'vscode' {

  // https://github.com/microsoft/vscode/issues/145234

  export interface TerminalExecutedCommand {
      /**
       * The {@link Terminal} the command was executed in.
       */
      terminal: Terminal;
      /**
       * The full command line that was executed, including both the command and the arguments.
       */
      commandLine: string | undefined;
      /**
       * The current working directory that was reported by the shell. This will be a {@link Uri}
       * if the string reported by the shell can reliably be mapped to the connected machine.
       */
      cwd: Uri | string | undefined;
      /**
       * The exit code reported by the shell.
       */
      exitCode: number | undefined;
      /**
       * The output of the command when it has finished executing. This is the plain text shown in
       * the terminal buffer and does not include raw escape sequences. Depending on the shell
       * setup, this may include the command line as part of the output.
       */
      output: string | undefined;
  }

  export namespace window {
      /**
       * An event that is emitted when a terminal with shell integration activated has completed
       * executing a command.
       *
       * Note that this event will not fire if the executed command exits the shell, listen to
       * {@link onDidCloseTerminal} to handle that case.
       */
      export const onDidExecuteTerminalCommand: Event<TerminalExecutedCommand>;
  }
}
如果您想尝试此功能,请查看相关的建议文件src/vscode-dts/vscode.proposed.terminalExecuteCommandEvent.d.ts。另请参阅https://code.visualstudio.com/api/advanced-topics/using-proposed-api

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接