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

我试图将一个参数从命令行传递到 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上有一个简单的测试项目可以说明这个问题。

This is using Gradle 1.0-rc-3. The NullPointer is from this line of code:

  args group

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

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

任何关于如何将命令行参数传递给 Gradle 的建议都值得赞赏。

206968 次浏览

project.group is a predefined property. With -P, you can only set project properties that are 没有 predefined. Alternatively, you can set Java system properties (-D).

正如在评论中提到的,我的解决方案被较新的内置 --args选项所取代。见 这个答案 from@madhead or 这个类似的问题


基于 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'

我的程序有两个参数,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]);

我的建筑,梯度

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

my terminal prompt:

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

从命令行传递一个 url,将 url 保存在 app gradle 文件中,如下所示 ResValue“ string”,“ url”,CommonUrl

and give a parameter in gradle.properties files as follows CommonUrl = “将你的网址放在这里或者可能是空的”

并将命令从命令行传递到命令行,如下所示 将你的网址放在这里

我已经编写了一段代码,将命令行参数放在 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(',')) + "]"
}

my task looks like this:

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

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

gradle runProgram -PcommandLineArgs="arg1 arg2 arg3 arg4"

自4.9级以来,Application plugin 理解 --args选项,所以传递参数就像这样简单:

建造,分级

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);
}
}

Bash

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

或者在 Windows 中,使用双引号:

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

您可以在 Gradle 使用自定义命令行选项:

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

自定义命令行选项在 Gradle 是 孵化特征5.0,但在 Gradle 是公开的。

Java solution

按照指示 给你:

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);
}
}

Then register it:

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")

如果您需要检查并设置 一次争吵,那么您的 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")
...

窗口中的 Sample 命令:

gradlew clean test -Pthreshold=0.25

这里有一个很好的例子:

Https://kb.novaordis.com/index.php/gradle_pass_configuration_on_command_line

可以传递参数然后在 ext 变量中提供默认值的详细信息,如下所示:

gradle -Dmy_app.color=blue

and then reference in Gradle as:

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

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

更多提示点击这里: https://kb.novaordis.com/index.php/Gradle_Variables_and_Properties

下面是 Kotlin DSL(build.gradle.kts)的解决方案。

我首先尝试将变量作为属性获取,如果是 null,则尝试从 OS 环境变量获取它(在 GitHub Actions 这样的 CI 中可能很有用)。

tasks.create("MyCustomTask") {
val songName = properties["songName"]
?: System.getenv("SONG_NAME")
?: error("""Property "songName" or environment variable "SONG_NAME" not found""")


// OR getting the property with 'by'. Did not work for me!
// For this approach, name of the variable should be the same as the property name
// val songName: String? by properties


println("The song name: $songName")
}

然后我们可以从命令行为属性传递一个值:

./gradlew MyCustomTask -PsongName="Black Forest"

Or create a file named 本地物业 at the root of the project and set the property:

songName=Black Forest

我们也可以将 添加一个 env 变量命名为 SONG_NAME,使用我们所需的值,然后运行任务:

./gradlew MyCustomTask