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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)