Go语言中的等价物是argv[0]是什么?

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

What's Go's equivalent of argv[0]?

问题

如何在运行时获取自己程序的名称?Go语言中有没有类似于C/C++的argv[0]的东西?对我来说,使用正确的名称生成用法很有用。

更新:添加了一些代码。

package main

import (
    "flag"
    "fmt"
    "os"
)

func usage() {
    fmt.Fprintf(os.Stderr, "用法: myprog [inputfile]\n")
    flag.PrintDefaults()
    os.Exit(2)
}

func main() {
    flag.Usage = usage
    flag.Parse()

    args := flag.Args()
    if len(args) < 1 {
        fmt.Println("缺少输入文件。")
        os.Exit(1)
    }
    fmt.Printf("正在打开 %s\n", args[0])
    // ...
}
英文:

How can I get my own program's name at runtime? What's Go's equivalent of C/C++'s argv[0]? To me it is useful to generate the usage with the right name.

Update: added some code.

package main

import (
    &quot;flag&quot;
    &quot;fmt&quot;
    &quot;os&quot;
)

func usage() {
    fmt.Fprintf(os.Stderr, &quot;usage: myprog [inputfile]\n&quot;)
    flag.PrintDefaults()
    os.Exit(2)
}

func main() {
    flag.Usage = usage
    flag.Parse()

    args := flag.Args()
    if len(args) &lt; 1 {
        fmt.Println(&quot;Input file is missing.&quot;);
        os.Exit(1);
    }
    fmt.Printf(&quot;opening %s\n&quot;, args[0]);
    // ...
}

答案1

得分: 167

import "os"
os.Args[0] // 正在运行的命令的名称
os.Args1 // 第一个命令行参数, ...

参数在os包中被公开 http://golang.org/pkg/os/#Variables

如果你要处理参数,首选的方式是使用flag包 http://golang.org/pkg/flag。特别是对于你的情况,使用flag.Usage

针对你给出的示例,更新如下:

func usage() {
fmt.Fprintf(os.Stderr, "用法:%s [inputfile]\n", os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}

应该可以解决问题。

英文:
import &quot;os&quot;
os.Args[0] // name of the command that it is running as
os.Args[1] // first command line parameter, ...

Arguments are exposed in the <code>os</code> package http://golang.org/pkg/os/#Variables

If you're going to do argument handling, the <code>flag</code> package http://golang.org/pkg/flag is the preferred way. Specifically for your case flag.Usage

Update for the example you gave:

func usage() {
    fmt.Fprintf(os.Stderr, &quot;usage: %s [inputfile]\n&quot;, os.Args[0])
    flag.PrintDefaults()
    os.Exit(2)
}

should do the trick

答案2

得分: 23

使用os包中的os.Args[0]

package main
import "os"
func main() {
    println("我是", os.Args[0])
}
英文:

use os.Args[0] from the os package

package main
import &quot;os&quot;
func main() {
    println(&quot;I am &quot;, os.Args[0])
}

huangapple
  • 本文由 发表于 2010年7月29日 02:11:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/3356011.html
匿名

发表评论

匿名网友

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

确定