如何将参数从命令行传递到Gradle


105

我试图将参数从命令行传递给Java类。我关注了这篇文章:http : //gradle.1045684.n5.nabble.com/Gradle-application-plugin-question-td5539555.html,但是该代码对我不起作用(也许不是JavaExec的意思?)。这是我尝试过的:

task listTests(type:JavaExec){
    main = "util.TestGroupScanner"
    classpath = sourceSets.util.runtimeClasspath
    // this works...
    args 'demo'
    /*
    // this does not work!
    if (project.hasProperty("group")){
        args group
    }
    */
}

上面的硬编码args值的输出为:

C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests
:compileUtilJava UP-TO-DATE
:processUtilResources UP-TO-DATE
:utilClasses UP-TO-DATE
:listTests
Received argument: demo

BUILD SUCCESSFUL

Total time: 13.422 secs

但是,一旦我更改代码以使用hasProperty部分并在命令行上将“ demo”作为参数传递,就会得到NullPointerException:

C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle>g listTests -Pgroup=demo -s

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\ws\svn\sqe\sandbox\selenium2forbg\testgradle\build.gradle' line:25

* What went wrong:
A problem occurred evaluating root project 'testgradle'.
> java.lang.NullPointerException (no error message)

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project
 'testgradle'.
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:127)
    at org.gradle.configuration.BuildScriptProcessor.evaluate(BuildScriptProcessor.java:38) 

http://gradle.1045684.n5.nabble.com/file/n5709919/testgradle.zip有一个简单的测试项目,可以说明此问题。

这是使用Gradle 1.0-rc-3。NullPointer来自以下代码行:

args group 

我在任务定义之前添加了以下分配,但是并没有改变结果:

group = hasProperty('group') ? group : 'nosuchgroup' 

任何有关如何将命令行参数传递给gradle的指针表示赞赏。


TNX很多@Joshua Goldberg。一个参数的示例:stackoverflow.com/a/58202665/2201814
MHSFisher

Answers:



56

在Peter N的答案的基础上,这是一个如何添加(可选)用户指定的参数以传递给JavaExec任务的Java main的示例(因为您不能出于引用的原因而手动设置'args'属性)。

将此添加到任务:

task(runProgram, type: JavaExec) {

  [...]

  if (project.hasProperty('myargs')) {
      args(myargs.split(','))
  }

...并像这样在命令行运行

% ./gradlew runProgram '-Pmyargs=-x,7,--no-kidding,/Users/rogers/tests/file.txt'

2
我怎样才能拥有单独的参数?例如:gradle run -Purl='localhost', -Pport='8080', -Pusername='admin' build.gradle中的代码应该是什么样?
托马斯

@Tomas我建议为此充实一个顶级问题。(无论如何,我对这种情况的了解还不够,以至于不能自己在这里给出快速的内联答案。)
Joshua Goldberg

1
不用担心,已经做完并在这里
Tomas

28

我的程序带有两个参数args [0]和args [1]:

public static void main(String[] args) throws Exception {
    System.out.println(args);
    String host = args[0];
    System.out.println(host);
    int port = Integer.parseInt(args[1]);

我的build.gradle

run {
    if ( project.hasProperty("appArgsWhatEverIWant") ) {
        args Eval.me(appArgsWhatEverIWant)
    }
}

我的终端提示:

gradle run  -PappArgsWhatEverIWant="['localhost','8080']"

17

从Gradle 4.9开始,应用程序插件了解--args选项,因此传递参数非常简单:

build.gradle

plugins {
    id 'application'
}

mainClassName = "my.App"

src / main / java / my / App.java

public class App {
    public static void main(String[] args) {
        System.out.println(args);
    }
}

重击

./gradlew run --args='This string will be passed into my.App#main arguments'

15

可以使用Gradle中的自定义命令行选项来生成类似以下内容的结果:

./gradlew printPet --pet="puppies!"

但是,Gradle中的自定义命令行选项是一个孵化功能

Java解决方案

要的东西最终会像这样按照指示在这里

import org.gradle.api.tasks.options.Option;

public class PrintPet extends DefaultTask {
    private String pet;

    @Option(option = "pet", description = "Name of the cute pet you would like to print out!")
    public void setPet(String pet) {
        this.pet = pet;
    }

    @Input
    public String getPet() {
        return pet;
    }

    @TaskAction
    public void print() {
        getLogger().quiet("'{}' are awesome!", pet);
    }
}

然后注册:

task printPet(type: PrintPet)

现在您可以执行以下操作:

./gradlew printPet --pet="puppies"

输出:

小狗!是真棒!

Kotlin解决方案

open class PrintPet : DefaultTask() {

    @Suppress("UnstableApiUsage")
    @set:Option(option = "pet", description = "The cute pet you would like to print out")
    @get:Input
    var pet: String = ""

    @TaskAction
    fun print() {    
        println("$pet are awesome!")
    }
}

然后使用以下命令注册任务:

tasks.register<PrintPet>("printPet")

5

如果需要检查并设置一个参数,则build.gradle文件将如下所示:

....

def coverageThreshold = 0.15

if (project.hasProperty('threshold')) {
    coverageThreshold = project.property('threshold').toString().toBigDecimal()
}

//print the value of variable
println("Coverage Threshold: $coverageThreshold")
...

Windows中的Sample命令:

gradlew清洁测试-Pthreshold = 0.25


4

我编写了一段代码,将命令行参数放入gradle期望的格式。

// this method creates a command line arguments
def setCommandLineArguments(commandLineArgs) {
    // remove spaces 
    def arguments = commandLineArgs.tokenize()

            // create a string that can be used by Eval 
            def cla = "["
            // go through the list to get each argument
            arguments.each {
                    cla += "'" + "${it}" + "',"
            }

    // remove last "," add "]" and set the args 
    return cla.substring(0, cla.lastIndexOf(',')) + "]"
}

我的任务看起来像这样:

task runProgram(type: JavaExec) {
    if ( project.hasProperty("commandLineArgs") ) {
            args Eval.me( setCommandLineArguments(commandLineArgs) )
    }
}

要从命令行传递参数,请运行以下命令:

gradle runProgram -PcommandLineArgs="arg1 arg2 arg3 arg4"    

1

这里有一个很好的例子:

https://kb.novaordis.com/index.php/Gradle_Pass_Configuration_on_Command_Line

您可以传递哪些细节,然后在ext变量中提供默认值,如下所示:

gradle -Dmy_app.color=blue

然后在Gradle中引用为:

ext {
   color = System.getProperty("my_app.color", "red");
}

然后在构建脚本中的任何地方都可以将其引用为课程,而在任何地方都可以将其引用为 project.ext.color

此处提供更多提示:https : //kb.novaordis.com/index.php/Gradle_Variables_and_Properties


-4

从命令行传递一个url,如下所示将您的url保留在应用gradle文件中: resValue“ string”,“ url”,CommonUrl

并在gradle.properties文件中提供一个参数,如下所示 CommonUrl =“在此处输入您的网址,或者可能为空”

并从命令行向命令行传递命令,如下所示: gradle assembleRelease -Pcommanurl =在此处输入您的URL

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.