【问题标题】:Run a command line with Gradle and Save the output result使用 Gradle 运行命令行并保存输出结果
【发布时间】:2022-01-15 10:37:12
【问题描述】:

我想用 Gradle 运行一个命令行,该命令有输出。
我在 windows powershell 中运行此命令:
./mybat.bat myArgs 当我按回车键时,它会打印一些数字,如下所示:
123456 我想用 gradle 运行这个命令并保存这个结果(123456)
这是我在 android build.gradle 文件中编写的一些代码:

task getSomeOutput(type: Exec) {
    workingDir "${buildDir}/output"
    commandLine 'powershell', './mybat.bat' , 'foo'//this is myArgs for example
}

这工作并打印值 123456,但我想将它保存在变量中,我该怎么做?

【问题讨论】:

标签: android gradle build.gradle


【解决方案1】:

正如你在官方文档HERE中看到的那样

这可以通过以下任务来实现

task executeCMD(type:Exec) {
  workingDir '.'
  commandLine 'mybat.bat', '>', 'log.txt'
     doLast {
         println "Executed!"
     }
 }

这将发送mybat.bat 执行的输出并将结果设置到一个名为 log 的 txt 文件中。

. 是您拥有脚本的目录。

在我的例子中,它是一个项目根目录。

【讨论】:

    【解决方案2】:

    我发现的最佳方法是将 '/c' 添加到命令行参数并使用 standardOutput,这里有一些可能对其他人有帮助的代码:

    task getSomeOutput(type: Exec) {
        workingDir "${buildDir}/output"
        commandLine 'powershell', '/c', './mybat.bat' , 'foo'//this is myArgs for example
        standardOutput = new ByteArrayOutputStream()
        doLast {
            def result = standardOutput.toString()
            println "the result value is: $result"
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多