duanchui1251 2014-11-21 01:41
浏览 346
已采纳

cmd.Output返回奇怪的结果

I am a beginner in Golang. I wrote a function that will take variable args and pass it to another function that accepts variable args. I used "exec.Command()" for the second one. Here is my program

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")
}

I expected it to return the list of files in the current directory. Instead I get a strange result

# 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]

What am I doing wrong

  • 写回答

2条回答 默认 最新

  • dongtang9855 2014-11-21 01:43
    关注

    You are printing a byte slice.

    fmt.Println("Output =", out)
    

    Convert it to a string.

    fmt.Println("Output =", string(out))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算