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

在Windows的CMD或GOLAND Terminal运行Go程序时可能出现中文乱码,原因在于Go的UTF-8编码与CMD的GBK编码不匹配。解决方法包括:使用`chcp 65001`命令将CMD的代码页切换到UTF-8,或转换文件编码为GBK。

在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值