Windows中CMD下执行Go有中文乱码怎么办
在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 time1ms TTL=128 Reply from 127.0.0.1: bytes=32 time1ms TTL=128 Reply from 127.0.0.1: bytes=32 time1ms TTL=128 Reply from 127.0.0.1: bytes=32 time1ms 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有中文乱码怎么办”的内容就介绍到这,感谢各位的阅读,相信大家对Windows中CMD下执行Go有中文乱码怎么办已经有了进一步的了解。大家如果还想学习更多知识,欢迎关注网络,小编将为大家输出更多高质量的实用文章!
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Windows中CMD下执行Go有中文乱码怎么办
本文地址: https://pptw.com/jishu/653742.html