go中获取各种路径

2016/7/22 文章分类: GO语言技巧
  1. 执行用户当前所在路径:

    
    os.Getwd()
    
    
  2. 执行程序所在路径:

    执行程序文件相对路径:

    
    file, _ := exec.LookPath(os.Args[0])
    
    

    执行程序所在的绝对路径:

    (使用下面一套方法)

    
    file, _ := exec.LookPath(os.Args[0])
    log.Println("file:", file)
    dir,_ := path.Split(file)
    log.Println("dir:", dir)
    os.Chdir(dir)
    wd, _ := os.Getwd()
    log.Println("wd:", wd)
    
    

    比如这个程序

    package main
    import(
        "os"
        "log"
        "os/exec"
        "path"
    )
    func main() {
        file, _ := os.Getwd()
        log.Println("current path:", file)
        file, _ = exec.LookPath(os.Args[0])
        log.Println("exec path:", file)
        dir,_ := path.Split(file)
        log.Println("exec folder relative path:", dir)
        os.Chdir(dir)
        wd, _ := os.Getwd()
        log.Println("exec folder absolute path:", wd)
    }
    
    

    可执行文件我放在/home/houqun/handcode/test
    我执行的路径是/home/houqun/

    返回结果:

    [houqun@HouTekiMacbook ~]$ handcode/test
    2013/02/06 11:09:07 current path: /home/houqun
    2013/02/06 11:09:07 exec path: handcode/test
    2013/02/06 11:09:07 exec folder relative path: handcode/
    2013/02/06 11:09:07 exec folder absolute path: /home/houqun/handcode