Golang – flag.Arg(0)返回的是通过exec.cmd传递的参数的索引1,而不是索引0。

huangapple go评论65阅读模式
英文:

Golang - flag.Arg(0) returns index 1 instead of index 0 of arguments passed by exec.cmd

问题

我目前在我的bar应用程序中有一个类似这样的东西

flag.Parse()
str := flag.Arg(0)
fmt.println(str)

现在在我的foo应用程序中有类似这样的东西

var stdout, stderr bytes.Buffer
cmd := exec.Cmd{
    Path:   c.Path,
    Args:   c.Args,
    Env:    c.Env,
    Stdin:  bytes.NewReader(b),
    Stdout: &stdout,
    Stderr: &stderr,
}

if err := cmd.Start(); err != nil {
    return err
}

现在在上述代码中,c.Args = [1,2,3]

foo程序试图调用bar程序,而bar显示的是2
我如何使bar显示1而不是2。

我知道flag.Parse忽略了第一个参数。我如何告诉它读取第一个参数(索引0)使用flag.Arg()

英文:

I currently have something in my bar app that looks like this

flag.Parse()
str := flag.Arg(0)
fmt.println(str)

Now in my foo app I have something like this

var stdout, stderr bytes.Buffer
	cmd := exec.Cmd{
		Path:   c.Path,
		Args:   c.Args,
		Env:    c.Env,
		Stdin:  bytes.NewReader(b),
		Stdout: &stdout,
		Stderr: &stderr,
	}

	if err := cmd.Start(); err != nil {
		return err
	}

Now in the above c.Args = [1,2,3]

foo program attempts to call into bar program and bar displays 2
How do I make bar display 1 instead.

I know flag.parse ignores the first parameter. How do I tell read the first parameter (index 0) using flag.Arg()

答案1

得分: 2

Cmd.Args 包括命令名称。flag.Arg(0) 是命令名称和标志之后的第一个参数。

通过将命令名称添加到 Cmd.Args 中进行修复。

cmd := exec.Cmd{
    Path:   c.Path,
    Args:   append([]string{c.Path}, c.Args...),
    Env:    c.Env,
    Stdin:  bytes.NewReader(b),
    Stdout: &stdout,
    Stderr: &stderr,
}
英文:

Cmd.Args includes the command name. flag.Arg(0) is the first argument after the command name and flags.

Fix by adding the command name to Cmd.Args.

cmd := exec.Cmd{
    Path:   c.Path,
    Args:   append([]string{c.Path}, c.Args...),
    Env:    c.Env,
    Stdin:  bytes.NewReader(b),
    Stdout: &stdout,
    Stderr: &stderr,
}

huangapple
  • 本文由 发表于 2022年12月15日 07:58:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/74805471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定