如何检测当前终端编码并将用户输入与utf8相互转换?

How to detect current terminal encoding and convert user input to and from utf8?

提问人:man3 提问时间:10/6/2016 最后编辑:Jonathan Hallman3 更新时间:10/15/2022 访问量:2392

问:

我正在编写一个接受用户输入的 golang 命令行程序。此输入字符串必须转换为 UTF-8 并发送到另一台服务器进行处理。在 Linux 上,终端编码几乎总是 UTF-8,但在 Windows 中似乎并非如此。我尝试使用 Windows 上的代码页设置为 65001

chcp 65001

并确保终端字体设置为 Lucida 控制台。但是,读取的字节数

fmt.Scanf()

不是 UTF-8 格式。我希望能够检测字符编码并将字符串转换为 UTF-8。同样,在打印到屏幕上之前,我应该能够从 UTF-8 转换为本地编码。

Python 似乎具有“locale”包,可以获取默认编码、解码和编码字符串到任何指定的编码。golang 有等价物吗?

大多数 stackoverflow 讨论都指向使用 chcp 65001 将 Windows 终端上的编码更改为 UTF-8。这似乎对我不起作用。

func main() {
    foo := ""
    fmt.Printf("Enter: ")
    if _, err := fmt.Scanln(&foo) ; err != nil {
        fmt.Println("Error while scanning: ", err)
    }
    fmt.Printf("Scanned bytes: % x", foo)
    fmt.Println()
}

在 Linux 上:

// ASCII
$ go run test.go
Enter: hello
Scanned bytes: 68 65 6c 6c 6f

// Unicode
$ go run test.go
Enter: ©
Scanned bytes: c2 a9

// Unicode
$ go run test.go
Enter: ΆΏΑΓΔΘΞ
Scanned bytes: ce 86 ce 8f ce 91 ce 93 ce 94 ce 98 ce 9e ce a3 ce a8 ce a9 ce aa ce ad ce b1 ce b2 ce ba

在 Windows 上:

PS C:\> chcp
Active code page: 437

PS C:\> go run .\test.go
Enter: hello
Scanned bytes: 68 65 6c 6c 6f

PS C:\> go run .\test.go
Enter: ΆΏΑΓΔΘΞ
Scanned bytes: 3f 3f 61

// Change to Unicode
PS C:\> chcp 65001
Active code page: 65001
PS C:\> go run .\test.go
Enter: ΆΏΑΓΔΘΞ
Error while scanning:  EOF
Scanned bytes:

感谢任何帮助/指示。

Windows Go UTF-8 字符编码 跨平台

评论

0赞 Koala Yeung 10/6/2016
我不认为终端环境有公开编码的标准方法(因为您包括 Windows)。我能想到的最好的解决方案是为此手动添加环境变量,然后用 .os.Getenv()
0赞 man3 10/6/2016
谢谢,@KoalaYeung。你知道在Windows环境中的golang中如何处理unicode吗?Scanf/bufio.read 似乎不读取非 UTF-8 输入。
0赞 Koala Yeung 10/6/2016
不好意思。我没有使用 Golang 的 Windows 经验。我读过一些文章,说你可以把代码页改成UTF-8。你认为这有帮助吗?chcp 65001
1赞 man3 10/6/2016
显然没有。我在问题中提到了这一点。
1赞 man3 10/8/2016
@KoalaYeung 是的,我尝试了 iconv,但我再次需要首先确定终端编码。目前,我计划在 go 程序中使用一些 C 代码。nl_langinfo(CODESET)

答:

-1赞 Seyed Hossein Hosseini motlagh 10/15/2022 #1

我在窗口中运行此代码,并使用 git bash 和 poweshell 等在终端中检查它,它工作正常。

也许是您的系统语言设置的问题。

有关 UTF8 的更多信息,我建议您阅读此软件包文档