gpt4 book ai didi

go - cmd.Output 返回奇怪的结果

转载 作者:IT王子 更新时间:2023-10-29 01:33:46 26 4
gpt4 key购买 nike

我是 Golang 的初学者。我写了一个函数,它将接受变量 args 并将其传递给另一个接受变量 args 的函数。第二个我使用了“exec.Command()”。这是我的程序

package main

import "fmt"
import "os/exec"

func execute(command string, parameters ...string) {
cmd := exec.Command(command, parameters...)
fmt.Println("Path =", cmd.Path, "Args =", cmd.Args, "Dir =", cmd.Dir)
out,_ := cmd.Output()
fmt.Println("Output =", out)
}

func main() {
execute("ls", "-l")
}

我希望它返回当前目录中的文件列表。相反,我得到了一个奇怪的结果

# go build command.go 
#./command
Path = /bin/ls Args = [ls -l] Dir =
Output = [116 111 116 97 108 32 57 49 52 52 10 45 114 119 120 114 45 120 114 45 120 32 49 32 114 111 111 116 32 114 111 111 116 32 50 55 53 55 57 53 50 32 78 111 118 32 50 48 32 49 55 58 50 54 32 99 111 109 109 97 110 100 10 45 114 119 45 114 45 45 114 45 45 32 49 32 114 111 111 116 32 114 111 111 116 32 32 32 32 32 51 48 55 32 78 111 118 32 50 48 32 49 55 58 50 54 32 99 111 109 109 97 110 100 46 103 111 10 45 114 119 120 114 45 120 114 45 120 32 49 32 114 111 111 116 32 114 111 111 116 32 51 52 48 49 48 51 50 32 78 111 118 32 50 48 32 49 53 58 52 51 32 110 101 120 117 115 49 48 48 48 118 10 45 114 119 45 114 45 45 114 45 45 32 49 32 114 111 111 116 32 114 111 111 116 32 32 32 32 56 57 48 52 32 78 111 118 32 50 48 32 49 53 58 52 51 32 110 101 120 117 115 49 48 48 48 118 46 103 111 10 45 114 119 120 114 45 120 114 45 120 32 49 32 114 111 111 116 32 114 111 111 116 32 51 49 55 53 52 48 48 32 78 111 118 32 50 48 32 49 55 58 50 52 32 116 101 115 116 110 101 116 10 45 114 119 45 114 45 45 114 45 45 32 49 32 114 111 111 116 32 114 111 111 116 32 32 32 32 32 52 55 56 32 78 111 118 32 50 48 32 49 55 58 50 53 32 116 101 115 116 110 101 116 46 103 111 10]

我做错了什么

最佳答案

您正在打印一个字节 slice 。

fmt.Println("Output =", out)

将其转换为字符串

fmt.Println("Output =", string(out))

关于go - cmd.Output 返回奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com