douxie0824 2015-09-06 13:45
浏览 47
已采纳

如何在go lang中将标志传递给命令?

I have been trying to run a command and parse the output in golang. Here is a sample of what I am trying to do:

package main

import (
        "fmt"
    "os/exec"
)

func main() {
    out,err := exec.Command("ls -ltr").Output()
        if err != nil {
                fmt.Println("Error: %s", err)
        }
    fmt.Printf("%s",out)
}

Now, when I am trying to run "ls -ltr", I get this error:

Error: %s exec: "ls -ltr": executable file not found in $PATH

So, basically go is looking for whole "ls -ltr" in PATH. And it's not there obviously. Is there any way I can pass a flag to any argument?TIA.

  • 写回答

1条回答 默认 最新

  • dpj0015 2015-09-06 13:49
    关注

    You pass arguments to the program by passing more arguments to the function - it's variadic:

    out,err := exec.Command("ls","-ltr").Output()
    

    https://golang.org/pkg/os/exec/#Command

    This is a pretty common convention with exec-style functions which you will see in most languages. The other common pattern is builders.


    Sometimes the layout of arguments you need to pass won't be known at compile-time (though it's not a good idea to send arbitrary commands to the system - stay safe!). If you want to pass an unknown number of arguments, you can use an array with some special syntax:

    // Populate myArguments however you like
    myArguments := []string{"bar","baz"}
    
    // Pass myArguments with "..." to use variadic behaviour
    out,err := exec.Command("foo", myArguments...).Output()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?