编程语言
首页 > 编程语言> > 通过传递参数和结果从Java调用Python代码

通过传递参数和结果从Java调用Python代码

作者:互联网

谁能给我展示一个通过传递参数并返回结果从Java代码调用python脚本的简单示例(java python代码)?

解决方法:

尝试使用Java ScriptEngine以Jython的身份运行代码.

示例程序:

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

public class Main {

     /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

        // Using the eval() method on the engine causes a direct
        // interpretataion and execution of the code string passed into it
        engine.eval("import sys");
        engine.eval("print sys");

        // Using the put() method allows one to place values into
        // specified variables within the engine
        engine.put("a", "42");

        // As you can see, once the variable has been set with
        // a value by using the put() method, we an issue eval statements
        // to use it.
        engine.eval("print a");
        engine.eval("x = 2 + 2");

        // Using the get() method allows one to obtain the value
        // of a specified variable from the engine instance
        Object x = engine.get("x");
        System.out.println("x: " + x);
    }

}

您需要在类路径中包含jython引擎jar.寻找它here

标签:parameters,jython,python,java
来源: https://codeday.me/bug/20191028/1955942.html