Home > Backend Development > Golang > Golang - flag.Arg(0) returns index 1 of the argument passed by exec.cmd instead of index 0

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

WBOY
Release: 2024-02-10 14:39:08
forward
551 people have browsed it

Golang - flag.Arg(0) 返回 exec.cmd 传递的参数的索引 1 而不是索引 0

Golang is a fast, efficient and reliable programming language, and flag.Arg(0) is a commonly used function in Golang, used to return the parameters passed by exec.cmd Index 1. However, PHP editor Zimo pointed out that the behavior of this function is not as expected, and it actually returns index 1 instead of index 0. This problem may cause errors in the processing of parameters by the program. In this article, we will explain the cause of this problem and provide solutions to help developers use the flag.Arg(0) function correctly.

Question Content

I have some content in my current bar application that looks like this

flag.parse()
str := flag.arg(0)
fmt.println(str)
Copy after login

Now in my foo application 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
    }
Copy after login

Now c.args above = [1,2,3]

foo program tries to call bar program, bar displays 2 How to make the column display 1.

I know flag.parse Ignore the first parameter. How to read the first argument (index 0) using flag.arg()

Workaround

cmd.args Contains the command name. flag.arg(0) is the first argument after the command name and flag.

Fixed 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,
}
Copy after login

The above is the detailed content of Golang - flag.Arg(0) returns index 1 of the argument passed by exec.cmd instead of index 0. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template