How to capture arguments passed to a Groovy script?

本小妞迷上赌 提交于 2019-12-18 10:58:14

问题


I am just starting out with Groovy. I couldn't find any examples anywhere of how to handle arguments to a Groovy script and so I hacked this method myself. There must be a better way of doing this? If so, I am looking for this better way, since I am probably overlooking the obvious.

import groovy.lang.Binding;
Binding binding = new Binding();
int x = 1
for (a in this.args) {
  println("arg$x: " + a)
  binding.setProperty("arg$x", a);
  x=x+1
}
println binding.getProperty("arg1")
println binding.getProperty("arg2")
println binding.getProperty("arg3")

回答1:


If you want more advanced parsing than just getting the arguments you can use the Groovy CliBuilder to help you. It helps you with commandline flags, optional arguments and printing the usage instruction.

Checkout CliBuilder's Javadoc or MrHakis post about it.




回答2:


Sorry about asking the question. I just figured it out:

println args[0]
println args[1]
println args[2]



回答3:


The simplest is just to use this.args as an array e.g.:

test.groovy

println this.args[0]

Call:

C:>groovy test this

Output:

this



回答4:


try this:

args.each{println it}



回答5:


It is very much similar to Java and you can use the same java syntax. For eg.

class TestExecutor {

    public static void main(def args) {
        println("Printing arguments");
        for(String arguments : args) {
            println (arguments);
        }
    }

} 

Run it and you should see the arguments printed

C:\Users\athakur\Desktop>groovy TestExecutor.groovy test1 test2 test3
Aug 16, 2014 11:47:56 AM org.codehaus.groovy.runtime.m12n.MetaInfExtensionModule
 newModule
WARNING: Module [groovy-nio] - Unable to load extension class [org.codehaus.groo
vy.runtime.NioGroovyMethods]
Printing arguments
test1
test2
test3

Also note if you do not provide main method or provide one like in above example then you can get arguments as args[i] but you can change the name of the array (again same as java). So you can have something like -

public static void main(def argsNew) {
    println("Printing arguments");
    for(String arguments : argsNew) {
        //using args in above for loop will throw error
        println (arguments);
    }
}

Point being it's not something that is hard-coded. Finally as suggested in other answer you can always use CliBuilder for smart parsing. But again in that too it internally used def options = cli.parse(args).



来源:https://stackoverflow.com/questions/6367384/how-to-capture-arguments-passed-to-a-groovy-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!