【问题标题】:Setting environment variables from Gradle从 Gradle 设置环境变量
【发布时间】:2012-02-06 00:16:45
【问题描述】:

我需要从 Gradle 执行依赖于环境变量的 Ant 脚本。 Ant 使用<property environment="env"/>。

我尝试在 Gradle 中执行 env.foo="bar",但它引发了 Groovy 异常。

将环境变量从 Gradle 传递到 Ant 的正确方法是什么?

【问题讨论】:

  • 您是否尝试通过ant.importBuild 'build.xml' 使用Ant 构建脚本?
  • @Benjamin 这就是我想要完成的。不幸的是,旧版 Ant 脚本依赖于几个环境变量。

标签: ant environment-variables gradle


【解决方案1】:

@Sergey 接受的解决方案:

ant.project.properties['env.foo'] = 'bar'

在gradle 2.9 和ant 1.9.7 上对我不起作用。 那没有抛出任何错误,但什么也不做。确实,如果您查看代码implemented as:

public Hashtable<String, Object> getProperties() {
    return PropertyHelper.getPropertyHelper(this).getProperties();
}

org.apache.tools.ant.PropertyHelper#getProperties is:

public Hashtable<String, Object> getProperties() {
    //avoid concurrent modification:
    synchronized (properties) {
        return new Hashtable<String, Object>(properties);
    }
}

所以它做了显式复制,它不能工作。

正确的做法在gradle文件中:

ant.project.setProperty('env.foo', 'bar')

Documentation 提及其他几种方式(注意,没有项目):

ant.buildDir = buildDir
ant.properties.buildDir = buildDir
ant.properties['buildDir'] = buildDir
ant.property(name: 'buildDir', location: buildDir)

【讨论】:

    【解决方案2】:

    从gradle 2.0 docs,我看到这样的事情是可能的

    test {
      environment "LD_LIBRARY_PATH", "lib"
    }
    

    或者在这种情况下可以使用这个

    systemProperty "java.library.path", "lib"
    

    【讨论】:

    • 我希望两年前我有 Gradle 2.0 :)
    • 我在我的 build.gradle 文件中尝试了这个(使用另一个变量名)。然后我像这样检查我的测试中的系统变量:assertTrue(System.getenv().containsKey("SOME_TEST_VAR")); 这给出了一个断言错误。所以,看起来环境变量没有设置。
    • 我收到一个错误Could not find method systemProperty() for arguments
    【解决方案3】:

    一般来说,从 Gradle 或 JVM 设置环境变量是不可能的,但可以像这样欺骗 Ant:

    ant.project.properties['env.foo'] = 'bar' 
    

    【讨论】:

    • 我收到一个错误:Could not find property '' on task '
    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 2016-07-19
    • 2014-12-17
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多