日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Windows下在CMD下執行Go出現中文亂碼的解決方法_Golang

作者:rznice ? 更新時間: 2021-12-06 編程語言

在cmd下運行go程序或者是GOLAND的Terminal下運行go程序會出現中文亂碼的情況。

go run ttypemain.go

???? Ping? [127.0.0.1] ???? 32 ????????:
???? 127.0.0.1 ????: ???=32 ???<1ms TTL=128
???? 127.0.0.1 ????: ???=32 ???<1ms TTL=128
???? 127.0.0.1 ????: ???=32 ???<1ms TTL=128
???? 127.0.0.1 ????: ???=32 ???<1ms TTL=128

127.0.0.1 ?? Ping ??????:
??? ?????: ????? = 4??????? = 4????? = 0 (0% ???)??
?????г????????(????????λ):

因為Go的編碼是 UTF-8,而CMD的活動頁是cp936(GBK),因此產生亂碼。

在中文Windows系統中,如果一個文本文件是UTF-8編碼的,那么在CMD.exe命令行窗口(所謂的DOS窗口)中不能正確顯示文件中的內容。在默認情況下,命令行窗口中使用的代碼頁是中文或者美國的,即編碼是中文字符集或者英文字符集。

在CMD或者Terminal下運行chcp查看活動頁代碼:

chcp
活動代碼頁: 936

得到的結果是 中文 936,UTF-8的代碼頁為65001,可以直接使用 chcp 65001 將活動代碼頁 改成65001,這樣UTF-8編碼的就顯示正常了。

chcp 65001
Active code page: 65001

go run ttypemain.go

Pinging  [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

?或者將中文轉成UTF-8的編碼,完整代碼如下:

package main

import (
 "bufio"
 "fmt"
 "golang.org/x/text/encoding/simplifiedchinese"
 "os/exec"
)

type Charset string

const (
 UTF8    = Charset("UTF-8")
 GB18030 = Charset("GB18030")
)

func main() {
 command := "ping"
 params := []string{"127.0.0.1","-t"}
 cmd := exec.Command(command, params...)
 stdout, err := cmd.StdoutPipe()
 if err != nil {
  fmt.Println(err)
  return
 }
 cmd.Start()
 in := bufio.NewScanner(stdout)
 for in.Scan() {
  cmdRe:=ConvertByte2String(in.Bytes(),"GB18030")
  fmt.Println(cmdRe)
 }
 cmd.Wait()
}

func ConvertByte2String(byte []byte, charset Charset) string {
 var str string
 switch charset {
 case GB18030:
  var decodeBytes,_=simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
  str= string(decodeBytes)
 case UTF8:
  fallthrough
 default:
  str = string(byte)
 }
 return str
}

正在 Ping 127.0.0.1 具有 32 字節的數據:
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128
來自 127.0.0.1 的回復: 字節=32 時間<1ms TTL=128

原文鏈接:https://blog.csdn.net/rznice/article/details/88122923

欄目分類
最近更新