【问题标题】:How to resolve user environment variables in filepath如何解析文件路径中的用户环境变量
【发布时间】:2019-03-27 21:33:35
【问题描述】:

Windows 上的 Golang。尝试使用

os.Open("%userprofile%\\myfile.txt")

获取 file path not found 和 golang 不会将 %userprofile% 解析到我的 C:\users\myusername 文件夹。

【问题讨论】:

  • 对于 POSIX shell,您可以使用 os.ExpandEnv,但它似乎不支持您正在使用的 %VAR% 样式变量。不过,实现您自己的版本将是微不足道的。

标签: windows go environment-variables


【解决方案1】:

要获得文件句柄,并使您的程序也具有一点可移植性,请尝试

userprofile := os.Getenv("USERPROFILE")
f, err := os.Open(path.Join(userprofile, "myfile.txt"))

os.Getenv() 将读取环境变量,path.Join() 将负责正确构建路径(因此无需执行\\)。

您可能还想查看os.LookupEnv(),而不是os.Getenv()。这将告诉您您要查找的环境变量是空的还是根本不存在。可以在 SO 上的this 答案中找到如何使用它来设置默认值的一个很好的示例。

【讨论】:

    【解决方案2】:
    userprofile := os.Getenv("USERPROFILE")
    os.Open(userprofile+"\\myfile.txt")
    

    【讨论】:

      【解决方案3】:

      刚刚写了一个包来做到这一点。欢迎反馈

      https://gitlab.com/stu-b-doo/windowspathenv/

      fmt.Println(windowspathenv.Resolve("%USERPROFILE%/Documents"))
      
      // C:\Users\YourName\Documents
      

      【讨论】:

        【解决方案4】:

        看看http://www.golangprograms.com/how-to-set-get-and-list-environment-variables.html

        您可以读取 'userprofile' 环境值并在将路径传递给 os.Open 之前构建路径

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-17
          • 2011-05-19
          • 2013-05-21
          • 2012-09-30
          • 2023-03-24
          • 1970-01-01
          • 2017-09-25
          • 1970-01-01
          相关资源
          最近更新 更多