4

Say I have a file:

i_want_this_name.go:

package main

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

How do I get the executing code's file's name in go?

Derek
  • 11,588
  • 25
  • 97
  • 153

2 Answers2

2

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

var Args []string

Args hold the command-line arguments, starting with the program name.

To use it, do the following:

package main

import "os"

func main(){
    filename := os.Args[0]
}
martinhans
  • 1,083
  • 7
  • 17
2

This should work for you:

package main

import (
  "fmt"
  "runtime"
)

func main() {
  _, fileName, lineNum, _ := runtime.Caller(0)
  fmt.Printf("%s: %d\n", fileName, lineNum)
}
plusmid
  • 181
  • 3