【问题标题】:gradle Exec block should not fail for non zero output ingradle Exec 块不应因非零输出而失败
【发布时间】:2015-11-28 08:40:25
【问题描述】:

我正在编写一个 gradle 任务。它调用的任务返回 3 表示成功运行,而不是 3。我该怎么做呢?

task copyToBuildShare(){
   def robocopySourceDir = "build\\outputs\\apk"
   def cmd = "robocopy "+ robocopySourceDir + " C:\\TEST *.* /MIR /R:5 2>&1"
   exec {
      ignoreExitValue = true
      workingDir '.'
      commandLine "cmd", "/c", cmd
      if (execResult.exitValue == 3) {
         println("It probably succeeded")
      }
   }
}

它给出了错误:

在任务中找不到属性“execResult”

我不想创建单独的任务。我希望它在 exec 块中。我做错了什么?

【问题讨论】:

  • 常见错误:“ignoreExitValue = true”之间不要包含等号('=')。它应该只是“ignoreExitValue true”

标签: android gradle android-gradle-plugin build.gradle gradlew


【解决方案1】:

project.exec() 有一个类型为 ExecResult 的返回值。

def result = exec {
    ignoreExitValue true 
    executable "cmd"
    args = ["/c", "exit", "1"]
}
println "exit value:"+result.getExitValue()

参考这里:

https://docs.gradle.org/current/dsl/org.gradle.api.Project.html#org.gradle.api.Project:exec(groovy.lang.Closure)

【讨论】:

  • 这应该是所问问题的答案。接受的答案提出了一个很好的建议,但并没有真正回答直接的问题。相反,它只是提供了另一种方式。至少这应该添加到接受答案中,并建议替代方式作为更好的方法。
【解决方案2】:

您需要指定此任务的类型为 Exec。这是通过像这样指定任务类型来完成的

task testExec(type: Exec) {

}

在您的特定情况下,您还需要确保在 exec 完成之前不要尝试获取 execResult,这可以通过将检查包装在 doLast 中来完成。

task testExec(type: Exec) {
    doLast {
        if (execResult.exitValue == 3) {
            println("It probably succeeded")

        }
    }
}

这里是一个执行ls并检查其返回值的例子

task printDirectoryContents(type: Exec) {

    workingDir '.'
    commandLine "sh", "-c", "ls"

    doLast{
        if (execResult.exitValue == 0) {
            println("It probably succeeded")

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 2019-06-08
    • 1970-01-01
    • 2020-10-28
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多