通过传递参数和结果从 Java 调用 Python 代码 [英] Call Python code from Java by passing parameters and results

查看:26
本文介绍了通过传递参数和结果从 Java 调用 Python 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anyone show me a working simple example (java + python code) of calling python script from java code by passing parameters and getting back the results?

推荐答案

尝试使用 Java ScriptEngine 作为 Jython 运行代码.

Try using Java ScriptEngine to run the code as 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.寻找它这里

You'll need to include the jython engine jar in your classpath. look for it here

这篇关于通过传递参数和结果从 Java 调用 Python 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆