dongluojiao6322 2018-02-27 03:48
浏览 33
已采纳

是否可以捕获由外部命令设置的环境变量?

I have a script (on Windows) that sets a number of environment variables. I would like to execute this script in Go to set up environment variables for subsequent calls to a binary.

Something like this:

cmd1 := exec.Command("setup_env.bat")
cmd.Run()

// other_command.exe relies on environment variables
// set by setup_env.bat
cmd2 := exec.Command("some_binary.exe")
cmd2.Env = cmd1.Env
cmd2.Run()

However this doesn't work, as cmd1.Env is empty after calling cmd1.Run() (environment variables set in cmd1 don't seem to propagate to cmd1.Env). os.Environ() also seems unaffected after calling cmd1.Run().

If you're curious as to why I'm doing this, I'm trying to automate a task that normally requires the user to call setup_env.bat followed by other_command.exe in a command prompt. I do not own setup_env.bat, and it may change frequently, so I can't just set the environment variables myself in Go.

  • 写回答

1条回答 默认 最新

  • drl47263 2018-02-28 01:49
    关注

    I managed to produce the desired result with the following code:

    cmd := exec.Command("setup_env.bat", "&&", "some_binary.exe")
    cmd.Run()
    

    I also discovered it's possible to manually parse the environment variables by capturing stdout after printing the environment with SET. For example:

    func getEnv(command string) ([]string, error) {
        cmd := exec.Command(command, "&&", "SET")
        out, _ := cmd.StdoutPipe()
    
        err := cmd.Start()
        if err != nil {
            return nil, err
        }
    
        rawEnv, _ := ioutil.ReadAll(out)
    
        err = cmd.Wait()
        if err != nil {
            return nil, err
        }
    
        env := strings.Split(string(rawEnv), "
    ")
        return env[:len(env)-1], nil
    }
    
    // ...
    
    cmd := exec.Command("some_binary.exe")
    env, err := getEnv("setup_env.bat")
    if err != nil {
        log.Fatal(err)
    }
    cmd.Env = env // or os.Setenv(...) if you need it in current context
    cmd.Run()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line