如何在go lang中将标志传递给命令? [英] How to pass a flag to a command in go lang?

查看:49
本文介绍了如何在go lang中将标志传递给命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试运行命令并解析golang中的输出.这是我正在尝试做的一个示例:

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:

软件包主要

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

现在,当我尝试运行"ls -ltr"时,出现此错误:

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

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

因此,基本上,go在PATH中查找整个"ls -ltr".而且显然不存在.我可以通过任何方式将标志传递给任何参数吗?TIA.

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.

推荐答案

您可以通过向函数传递更多参数来将参数传递给程序-这是可变参数:

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

这是exec样式函数的非常常见的约定,您会在大多数语言中看到.另一个常见的模式是构建器.

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()

这篇关于如何在go lang中将标志传递给命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆