从Java调用Python并传递参数时出错

时间:2013-05-29 14:32:06

标签: java jython

以下是从Java调用Python的给定代码

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new test1( ).setVisible(true);
        }
    });
    try {
        PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
        PythonInterpreter interp = new PythonInterpreter();
        interp.set("firstName", args[0]);
        interp.set("lastName", args[1]);
        interp.execfile("‪C:\\Users\\priyank\\Desktop\\pythontest.py");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

我收到以下异常:

java.lang.ArrayIndexOutOfBoundsException: 0" error.. 

为什么我会收到此错误?

3 个答案:

答案 0 :(得分:0)

当您启动应用程序时,看起来您没有传递任何参数。 args-array为空(size = 0),但是您尝试访问第一个元素(索引0),该元素不存在。

答案 1 :(得分:0)

管道可以是更好的解决方案。看看这个帖子:

java: how to both read and write to & from process thru pipe (stdin/stdout)

答案 2 :(得分:0)

将值更改为

interp.set("firstName", args[1]);
interp.set("lastName", args[2]);

它会起作用,因为第一个值是python脚本文件名,但是我们没有添加它,请检查它。