Utilizing PythonInterpreter¶

本文详细介绍了如何使用Jython的PythonInterpreter直接嵌入到Java应用中,通过执行Python代码来增强Java的功能。利用PythonInterpreter,开发者可以无缝地在Java环境中运行Python脚本和模块,从而充分利用Python丰富的库和API。此外,通过Jython对象工厂设计模式,Java代码能够调用和操作Jython代码,实现跨语言的代码复用和集成。尽管jython.jar不再包含在Jython发行版中,但仍然可以通过JAR文件在Java应用中有效地使用Jython。

Chapter 10: Jython and Java Integration — Jython Book v1.0 documentation

Utilizing PythonInterpreter

A similar technique to JSR-223 for embedding Jython is making use
of the PythonInterpreter directly. This style of embedding code is
very similar to making use of a scripting engine, but it has the
advantage of working with Jython 2.5. Another advantage is that the
PythonInterpreter enables you to make use of PyObjects directly. In
order to make use of the PythonInterpreter technique, you only need
to have jython.jar in your classpath; there is no need to have an
extra engine involved.

Listing 10-9. Using PythonInterpreter

import org.python.core.PyException;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class Main {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) throws PyException {

        // Create an instance of the PythonInterpreter
        PythonInterpreter interp = new PythonInterpreter();

        // The exec() method executes strings of code
        interp.exec("import sys");
        interp.exec("print sys");

        // Set variable values within the PythonInterpreter instance
        interp.set("a", new PyInteger(42));
        interp.exec("print a");
        interp.exec("x = 2+2");

        // Obtain the value of an object from the PythonInterpreter and store it
        // into a PyObject.
        PyObject x = interp.get("x");
        System.out.println("x: " + x);
    }

}

In the class above, we make use of the PythonInterpreter to execute
Python code within the Java class. First, we create an instance of
the PythonInterpreter object. Next, we make exec() calls against it
to execute strings of code passed into it. Next we use the set()
method in order to set variables within the interpreter instance.
Lastly, we obtain a copy of the object that is stored in the
variable x within the interpreter. We must store that object as a
PyObject in our Java code.

Results

<module 'sys' (built-in)>
42
x: 4

The following is a list of methods available for use within a
PythonInterpreter object along with a description of
functionality.

Table 10-2.**PythonInterpreter Methods

MethodDescription
setIn(PyObject)Set the Python object to use for the standard input stream
setIn(java.io.Reader)Set a java.io.Reader to use for the standard input stream
setIn(java.io.InputStream)Set a java.io.InputStream to use for the standard input stream
setOut(PyObject)Set the Python object to use for the standard output stream
setOut(java.io.Writer)Set the java.io.Writer to use for the standard output stream
setOut(java,io.OutputStream)Set the java.io.OutputStream to use for the standard output stream
setErr(PyObject)Set a Python error object to use for the standard error stream
setErr(java.io.WriterSet a java.io.Writer to use for the standard error stream
setErr(java.io.OutputStream)Set a java.io.OutputStream to use for the standard error stream
eval(String)Evaluate a string as Python source and return the result
eval(PyObject)Evaluate a Python code object and return the result
exec(String)Execute a Python source string in the local namespace
exec(PyObject)Execute a Python code object in the local namespace
execfile(String filename)Execute a file of Python source in the local namespace
execfile(java.io.InputStream)Execute an input stream of Python source in the local namespace
compile(String)Compile a Python source string as an expression or module
compile(script, filename)Compile a script of Python source as an expression or module
set(String name, Object value)Set a variable of Object type in the local namespace
set(String name, PyObject value)Set a variable of PyObject type in the local namespace
get(String)Get the value of a variable in the local namespace
get(String name, Class<T> javaclassGet the value of a variable in the local namespace. The value will be returned as an instance of the given Java class.

Summary

Integrating Jython and Java is really at the heart of the Jython
language. Using Java within Jython works just as we as adding other
Jython modules; both integrate seamlessly. What makes this nice is
that now we can use the full set of libraries and APIs available to
Java from our Jython applications. Having the ability of using Java
within Jython also provides the advantage of writing Java code in
the Python syntax.

Utilizing design patterns such as the Jython object factory, we can
also harness our Jython code from within Java applications.
Although jythonc is no longer part of the Jython distribution, we
can still effectively use Jython from within Java. There are object
factory examples available, as well as projects such as PlyJy
(http://kenai.com/projects/plyjy) that give the ability to use
object factories by simply including a JAR in your Java
application.

We learned that there are more ways to use Jython from within Java
as well. The Java language added scripting language support with
JSR-223 with the release of Java 6. Using a jython engine, we can
make use of the JSR-223 dialect to sprinkle Jython code into our
Java applications. Similarly, the PythonInterpreter can be used
from within Java code to invoke Jython. Also keep an eye on
projects such as Clamp
(http://github.com/groves/clamp/tree/master): the Clamp project has
the goal to make use of annotations in order to create Java classes
from Jython classes. It will be exciting to see where this project
goes, and it will be documented once the project has been
completed.

In the next chapter, you will see how we can use Jython from within
integrated development environments. Specifically, we will take a
look at developing Jython with Eclipse and Netbeans. Utilizing an
IDE can greatly increase developer productivity, and also assist in
subtleties such as adding modules and JAR files to the classpath.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值