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, "usage: myprog [inputfile]\n")
flag.PrintDefaults()
os.Exit(2)
}


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


args := flag.Args()
if len(args) < 1 {
fmt.Println("Input file is missing.");
os.Exit(1);
}
fmt.Printf("opening %s\n", args[0]);
// ...
}
59884 次浏览
import "os"
os.Args[0] // name of the command that it is running as
os.Args[1] // first command line parameter, ...

参数在 oshttp://golang.org/pkg/os/#Variables中公开

如果要进行参数处理,flaghttp://golang.org/pkg/flag是首选的方法

更新你给出的例子:

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

应该能行

use os.Args[0] from the os package

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