提问人:man3 提问时间:10/6/2016 最后编辑:Jonathan Hallman3 更新时间:10/15/2022 访问量:2392
如何检测当前终端编码并将用户输入与utf8相互转换?
How to detect current terminal encoding and convert user input to and from utf8?
问:
我正在编写一个接受用户输入的 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:
感谢任何帮助/指示。
答:
-1赞
Seyed Hossein Hosseini motlagh
10/15/2022
#1
我在窗口中运行此代码,并使用 git bash 和 poweshell 等在终端中检查它,它工作正常。
也许是您的系统语言设置的问题。
有关 UTF8 的更多信息,我建议您阅读此软件包文档
评论
os.Getenv()
chcp 65001
nl_langinfo(CODESET)