您现在的位置是:网站首页> 编程资料编程资料

Windows下在CMD下执行Go出现中文乱码的解决方法_Golang_

2023-05-26 399人已围观

简介 Windows下在CMD下执行Go出现中文乱码的解决方法_Golang_

在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

到此这篇关于Windows下在CMD下执行Go出现中文乱码的解决方法的文章就介绍到这了,更多相关CMD下执行Go乱码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网