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

本文主要介绍了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 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中文乱码内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是Windows下CMD执行Go出现中文乱码的解决方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程