Windows下CMD执行Go出现中文乱码如何解决

本篇内容主要讲解“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% ��ʧ)��
�����г̵Ĺ���ʱ��(�Ժ���Ϊ��&lambda;):

因为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出现中文乱码如何解决”有了更深的了解,不妨来实际操作一番吧!这里是蜗牛博客网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接