如何在Golang中打印多行的执行输出

huangapple go评论72阅读模式
英文:

How do you print multiline exec output in golang

问题

我正在尝试编写一个简单的Go语言程序,用于列出目录中的文件。每当我的shell命令返回多行时,它在Go中被注册为一个数组。

例如,当我尝试以下代码时:

import (
	"log"
	"os/exec"
	"fmt"
)

func main() {
	out, err := exec.Command("ls").Output()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(out)
}

我得到的输出是[101 108 105 109 115 116 97 116 115 46 105 109 108 10 101 110 118 10 115 99 114 97 116 99 104 10 115 114 99 10]

我觉得这是一个常见的操作,但在这里找不到相关信息。

英文:

I'm trying to write a simple golang program that lists the files in a directory. Whenever my shell command yields multiple lines, it registers in Go as an array

For example, when i try the following:

import (
	"log"
	"os/exec"
	"fmt"
)
func main (){

	out,err := exec.Command("ls").Output()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(out)

}

I end up with the output [101 108 105 109 115 116 97 116 115 46 105 109 108 10 101 110 118 10 115 99 114 97 116 99 104 10 115 114 99 10]

I feel like this is a common thing to do but wasn't able to find it on here anywhere.

答案1

得分: 6

第一个值从Output的返回类型是[]bytefmt.Println显示每个切片元素的数值。

为了显示命令输出的期望结果,你可以将字节切片转换为字符串,或者使用带有%s占位符的格式化字符串:

fmt.Println(string(out))

或者:

fmt.Printf("%s\n", out)
英文:

The return type of the first value from Output is []byte. fmt.Println is displaying the numeric values of each slice element.

To show the desired result of the output of the command, you can either convert the byte slice to a string or use a format string with the %s verb:

fmt.Println(string(out))

Or:

fmt.Printf("%s\n", out)

huangapple
  • 本文由 发表于 2017年9月12日 05:27:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/46164618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定