英文:
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,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论