如何在 VSCode 调试器中模拟交互式控制台?

How can I simulate interactive console in VSCode debugger?

我正在尝试调试这个读取文本并通过 VSCode 调试器将其输出到控制台的 Go 程序。

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println(text)
}

它在终端上运行良好,但是当我使用 VSCode 调试它时,即使我聚焦调试输出也无法输入任何内容。

调试部分有一个控制台,但它是 REPL 评估器,因此它也与终端控制台无关。

如何在 VSCode 中启用控制台以便我可以向程序输入文本?

这后面是Microsoft/vscode-go issue 219,而且还在营业。

Yes - the VS Code debugger console doesn't currently support piping any input through to stdin.

FYI, you can tell the Code debugger to use an external console in the launch config:

"externalConsole": true

它有一个 possible workaround,使用远程调试 + vscode 任务,但这并不简单。

tasks.json:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "cd ${fileDirname} && dlv debug --headless --listen=:2345 --log --api-version=2",
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Connect to server",
            "type": "go",
            "request": "launch",
            "mode": "remote",
            "remotePath": "${fileDirname}",
            "port": 2345,
            "host": "127.0.0.1",
            "program": "${fileDirname}",
            "env": {},
            "args": []
        }
    ]
}

Run the task using shortcut key(command/control + shift + B), vscode will start a new shell and run the delve server.

Press F5 to debug the .go file. It works fine for me.

我使用这个解决方法解决了这个问题 - https://github.com/golang/vscode-go/issues/124#issuecomment-999064812