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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题