将命令行参数从java传递到jython / optparse

时间:2013-08-12 15:14:49

标签: jython optparse

我想从python包中创建一个jar文件。我正在使用maven的jython-compile-maven-plugin。棘手的部分似乎是对论点的处理。接收python包使用optparse,它在python端工作正常,但我很难通过java / jython提供参数。

我收到有关遗失参数的错误。现在我尝试为main()提供参数,但它不期望任何参数。

这就是我打电话给jar的方式:

java -jar target/metrics-0.2.0-jar-with-dependencies.jar -f sample.txt --format csv -q

Java started
5 Arguments: -f, sample.txt, --format, csv, -q, 
Exception in thread "main" javax.script.ScriptException: TypeError: main() takes no arguments (1 given) in <script> at line number 1

关于如何正确提供args的任何想法?

这是我的InitJython.java:

package org.testingsoftware.metrics;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.lang.StringUtils;

public class InitJython {

    public static void main(String[] args) throws ScriptException {
        System.out.println("Java started");
        System.out.print(args.length + " Arguments: ");
        for (String s : args) {
            System.out.print(s);
            System.out.print(", ");
        }
        System.out.println();
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

        // c.exec("try:\n  from metrics.metrics import main\n  main()\nexcept SystemExit:\n  pass");
        engine.eval("from metrics.metrics import main");
        engine.eval("main('" + StringUtils.join(args, " ") + "')");
        System.out.println("Java exiting");
    }

    public void run() throws ScriptException {
    }
}

1 个答案:

答案 0 :(得分:0)

这一行,

engine.eval("main('" + StringUtils.join(args, " ") + "')");

评估为

engine.eval("main('-f sample.txt --format csv -q')");

这意味着main() Python函数将收到一个参数(“1给定”,如错误消息中所述)。

为了使其有效,您可以使用main()看起来像这样:

def main(arg):
    # Split 'arg' to get the arguments that were given to InitJython 
    # on the command line as a list of strings
    args = arg.split()

    parser = OptionParser()
    parser.add_option("-f", dest="filename",
                      help="read from FILENAME")
    ...
    ...

    (opts, args) = parser.parse_args(args)