dongxue9997 2012-08-23 11:05
浏览 65
已采纳

查找可执行文件的路径

I compile a program with Go for various platforms and run it by calling a relative path or just by its name (if it is in the PATH variable).

Is it possible to find out where the executable is?

Say, my program is called "foo(.exe)". I can run ./foo, foo (if it's in the PATH), ../../subdir/subdir/foo.

I have tried to use os.Args[0] and I guess I should check if the program name contains something different besides "foo". If yes, use filepath.Abs, if no, use (I can't find the function name, there is a function that looks through the PATH to check where the program is).

  • 写回答

3条回答 默认 最新

  • dongyukui8330 2013-02-23 07:27
    关注

    Use package osext.

    It's providing function Executable() that returns an absolute path to the current program executable. It's portable between systems.

    Online documentation

    package main
    
    import (
        "github.com/kardianos/osext"
        "fmt"
    )
    
    func main() {
        filename, _ := osext.Executable()
        fmt.Println(filename)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)