如何将输出通过管道传输到 Visual Studio 代码中?

How do I pipe output into Visual Studio Code?

我想将命令的输出通过管道传输到 Visual Studio 代码中的新文本 window。

通常情况下,我会这样做:

echo foo | code

...但这似乎不起作用; Visual Studio 代码启动,但不显示输入。有没有办法在命令行上进行管道传输?

截至 2016 年 9 月,它似乎不受支持,但有一个未解决的问题来实现它:

https://github.com/Microsoft/vscode/issues/6161

自版本 1.19.1 起,您可以通过调用以下方式将输出通过管道传输到当前 window:

<command> | code -

如果您使用的是 1.19 或更早版本,则不需要 arg:

<command> | code

我正在使用 Ubuntu Gnome 17.10(Artful Aardvark),我 运行 Visual Studio 代码 v1.19.3。仅通过管道传输到 code 不足以装入标准输入。

$ ps aux | code
Run with 'code -' to read from stdin (e.g. 'ps aux | grep code | code -').

您必须添加 - 运算符:

$ ps aux | code -

这行得通,并打开一个由命令输出填充的新文本选项卡。

当我使用已接受的答案时,控制台被阻止,直到我关闭 VS Code 中的相应选项卡。由于我经常想在继续使用控制台的同时在 VS Code 中保持选项卡打开,因此我想出了这个解决方法:

ls > t; code t; rm t

它重定向到当前目录中的文件 t,告诉 VS Code 打开该文件,然后将其删除。您将在标记为 t (deleted).

的选项卡中看到 VS Code 中文件的内容

如果 VS Code 尚未打开,则需要稍微延迟(1 秒对我有用):

ls > t; code t; sleep 1; rm t

备注

  • 我在 Windows 10 上使用 Git Bash 或 PowerShell 7 对此进行了测试。
  • 当然,请注意您为一次性文件使用的名称,以免覆盖真实文件。

编辑:我为此创建了一个函数以放入我的 PowerShell 配置文件。

Function Out-Code {
    do {
        $filename = New-Guid
    } while (Test-Path $filename)
    $input > $filename
    code $filename
    Start-Sleep 1
    Remove-Item $filename
}
Set-Alias oc Out-Code

用法

ls | oc