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 ( "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]); // ... }
By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1] , and argv[argc] is always NULL.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. So no, it's only the program name if that name is available.
The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.
argv[argc] is a NULL pointer. argv[0] holds the name of the program. argv[1] points to the first command line argument and argv[n] points last argument.
import "os" os.Args[0] // name of the command that it is running as os.Args[1] // first command line parameter, ...
Arguments are exposed in the os
package http://golang.org/pkg/os/#Variables
If you're going to do argument handling, the flag
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, "usage: %s [inputfile]\n", os.Args[0]) flag.PrintDefaults() os.Exit(2) }
should do the trick
use os.Args[0]
from the os package
package main import "os" func main() { println("I am ", os.Args[0]) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With