How to get executable name in go?

Say I have a file:

i_want_this_name.go:

package main

func main(){
    filename := some_func() // should be "i_want_this_name"
}

How to get executable name in go?

+4
source share
2 answers

The command name can be found in the os.Args[0]as status in the documentation for the os package :

var Args []string

Args contain command line arguments starting with the program name.

To use it, do the following:

package main

import "os"

func main(){
    filename := os.Args[0]
}
+2
source

This should work for you:

package main

import (
  "fmt"
  "runtime"
)

func main() {
  _, fileName, lineNum, _ := runtime.Caller(0)
  fmt.Printf("%s: %d\n", fileName, lineNum)
}
+2
source

Source: https://habr.com/ru/post/1609254/


All Articles