On 8 January 2011 18:21, Michael Thomas Lee <bakato...@gmail.com> wrote:
> Hello, is there any way of getting Go to recognize the current working
> path?
> os.Getwd() and os.Getenv("PWD") both points to the home folder, while
> ".", or "./" does not get recognized at all.
path, err := os.Getwd()
if err != nil {
panic(err)
}
Anyway, os.Getwd() works fine on my machine (6g, 6l, Mac OS X 10.6.6),
just tested it now. What version of the compiler/OS are you using?
Also you can you try this simple program:
package main
import(
"fmt"
"os"
)
func main() {
fmt.Println(os.Getwd())
}
2011/1/8 Michael Thomas Lee <bakato...@gmail.com>:
Hi Michael,
The current working directory is the path your shell is currently at. If you want to obtain the path the executable is under, use the path of os.Args[0]
--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/blog
http://niemeyer.net/twitter
Just to elaborate. You can use exec.LookPath[1] to find the executable
in your PATH variable, use path.Split[2] to extract the directory and
then use os.Chdir[3] to change the working directory.
cat > example.go << EOF
package main
import (
"exec"
"os"
"path"
)
func main() {
file, _ := exec.LookPath(os.Args[0]) // [1]
println("file:", file)
dir, _ := path.Split(file) // [2]
println("dir:", dir)
os.Chdir(dir) // [3]
wd, _ := os.Getwd()
println("wd:", wd)
}
EOF
[1]: http://golang.org/pkg/exec/#LookPath
[2]: http://golang.org/pkg/path/#Split
[3]: http://golang.org/pkg/os/#Chdir
cheers,
chressie