【问题标题】:How to pass command line arguments to a custom Exec gradle task?如何将命令行参数传递给自定义 Exec gradle 任务?
【发布时间】:2021-03-31 01:57:31
【问题描述】:

我正在尝试将命令行参数传递给 Gradle Exec 任务。所以我想执行一个bash脚本并给它一个参数。但是,在没有参数的情况下执行脚本会很流畅。只是带有@Option 的参数本身在打印时给出了一个空值。我的代码如下

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


task buildSamples(type: SampleExecTask){
    command()   
}

class SampleExecTask extends Exec {
    private String argument;

    @Option(option = "argument", description = "An argument for the script")
    public void setSample(String argument) {
        this.argument = argument;
    }

    @Input
    public String getArgument() {
        return argument;
    }
    
    void command() {
        println(argument);
        commandLine 'sh', 'myBashScript.sh'
    }
}

有人知道为什么我的参数值为 null 并且没有设置吗? 提前致谢!

【问题讨论】:

    标签: gradle


    【解决方案1】:

    它确实被设置了,但不是在你引用它的时候。 Gradle 中的大多数对象都是延迟评估的,并且在配置时不能保证完全配置。

    如果您将command() 放在doFirst 块中,则它不应为空。

    但是,使用命令行选项中的额外参数来增加 Exec 任务的更正确方法可能是在 setter 中配置标准的 args 属性:

    // Groovy DSL
    task buildSamples(type: SampleExecTask)
    
    class SampleExecTask extends Exec {
        @Option(option = "argument", description = "An argument for the script")
        public void setSample(String argument) {
            args(argument)
        }
        
        // Base configuration can be set in the constructor
        SampleExecTask() {
            executable('sh')
            args('myBashScript.sh')
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多