记录一下短命令
package main
import (
"fmt"
"os/exec"
"runtime"
"syscall"
"golang.org/x/text/encoding/simplifiedchinese"
)
type Charset string
const (
UTF8 = Charset("UTF-8")
GB18030 = Charset("GB18030")
)
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
}
func main() {
cmd := exec.Command("cmd.exe", "/c", "ping", "192.168.42.221")
if runtime.GOOS == "windows" {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
//Start执行不会等待命令完成,Run会阻塞等待命令完成。
//err := cmd.Start()
//err := cmd.Run()
//cmd.Output()函数的功能是运行命令并返回其标准输出。
buf, err := cmd.Output()
cmdRe:=ConvertByte2String(buf,"GB18030")
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
status := exitErr.Sys().(syscall.WaitStatus)
switch {
case status.Exited():
fmt.Printf("Return exit error: exit code=%d\n", status.ExitStatus())
case status.Signaled():
fmt.Printf("Return exit error: signal code=%d\n", status.Signal())
}
} else {
fmt.Printf("Return other error: %s\n", err)
}
} else {
fmt.Println(string(cmdRe))
}
}
评论区