你如何确定当前正在运行的可执行文件的完整路径? [英] How do you determine the full path of the currently running executable in go?

查看:277
本文介绍了你如何确定当前正在运行的可执行文件的完整路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //快捷方式获取当前可执行文件的路径
func ExecPath()string {
var here = os.Args [0]
if!strings.HasPrefix(here,/){
here,_ = exec.LookPath( os.Args [0])
if!strings.HasPrefix(这里是/){
var wd,_ = os.Getwd()
here = path.Join(wd,在这里)
}
}
在这里返回
}



<但是它非常混乱,它根本不能在Windows上运行,而且它也不是ainly不在git-bash中。

有没有一种方法可以实现这个跨平台?



NB 。特别是args [0]取决于二进制文件的调用方式;它在某些情况下只是二进制本身,例如。 app或app.exe;所以你不能只用它。

解决方案

这是我认为可以在任何平台下工作的传统方式。

$ p $ import(
fmt
os
path / filepath


//获取当前可执行文件路径的快捷方式
func ExecPath()string {
var here = os.Args [0]
这里,err:= filepath.Abs​​(here)
if err!= nil {
fmt.Printf(怪异路径:%s \ n,err)
}
return here
}


I've been using this function on osx:

// Shortcut to get the path to the current executable                      
func ExecPath() string {                                                   
  var here = os.Args[0]                                                    
  if !strings.HasPrefix(here, "/") {                                       
    here, _ = exec.LookPath(os.Args[0])                                    
    if !strings.HasPrefix(here, "/") {                                     
      var wd, _ = os.Getwd()                                               
      here = path.Join(wd, here)                                           
    }                                                                      
  } 
  return here                                                              
}

...but its pretty messy, and it doesn't work on windows at all, and certainly not in git-bash on windows.

Is there a way of doing this cross platform?

NB. Specifically that args[0] depends on how the binary is invoked; it is in some cases only the binary itself, eg. "app" or "app.exe"; so you can't just use that.

解决方案

This is the traditional way of doing it which I think will work under any platform.

import (
    "fmt"
    "os"
    "path/filepath"
)

// Shortcut to get the path to the current executable                      
func ExecPath() string {
    var here = os.Args[0]
    here, err := filepath.Abs(here)
    if err != nil {
        fmt.Printf("Weird path: %s\n", err)
    }
    return here
}

这篇关于你如何确定当前正在运行的可执行文件的完整路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆