Jython Course Outline
Author: Dave Kuhlman Address: dkuhlman@rexx.com http://www.rexx.com/~dkuhlmanRevision: 1.1b Date: May 9, 2008 Copyright: Copyright (c) 2006 Dave Kuhlman. All Rights Reserved.
This software is subject to the provisions of the MIT License
http://www.opensource.org/licenses/mit-license.php.Abstract
This document provides an outline of an introductory
course on programming in Jython and connecting Jython to JavaContents
- 1 How-to Write Jython Code
- 2 Installing and Running Jython
- 3 Integrating Java into Jython/Python
- 4 Integrating Jython/Python into Java
- 4.1 Calling Jython from Java
- 4.2 Embedding Jython into Java
- 4.2.1 Why embedded Jython
- 4.2.2 Embedding Jython into Java is simple
- 4.2.3 Passing values into a Jython script
- 4.2.4 Initializing the interpreter
- 4.2.5 Retrieving values from a Jython script
- 4.2.6 There are also a few complexities
- 4.2.7 Exposing transparent objects
- 4.2.8 Exposing opaque objects
- 4.2.9 Type conversion
- 4.2.10 Using a custom class loader
- 4.2.11 Embedding a Jython console
- 4.3 Embedding Jython with the Java Scripting Engine
- 4.4 Compiling Jython code with jythonc
- 5 Deployment and Distribution
- 6 Integrating, Embedding, and Extending -- A Summary
- 7 Jython+Java -- Other Advanced Topics
- 8 Additional Exercises
- 9 References and Sources
1 How-to Write Jython Code
Jython is Python. That's one of its big advantages: you get two for
the price of one. If your learn Python, then you have also learned
Jython, and vice versa. If you already know Python, then you know
Jython.But, if you do know know Python or Jython, then here are good
training aids:2 Installing and Running Jython
2.1 Install Jython
You will need Java installed, of course. And, since you are likely
to want to use Jython class libraries from Jython, it is also likely
that you will want the Java SDK. Important: If more than one
version of Java is installed on your machine, make sure that when
you install Jython, you use the version of Java for which the SDK is
installed and the version of Java that you will be using when you
run Jython.Download the Jython installation jar file -- You can file the Jython
distribution here: Jython downloads --
http://jython.org/Project/download.html.Install Jython -- Follow the instructions at:
Jython installation --
http://jython.org/Project/installation.html:$ java -jar jython_installer-2.2.1.jarCommand line history -- On MS Windows, command line history for the
Jython interactive interpreter comes built-in. On Linux,
to get command line history, command line editing, and readline
support, follow the instructions here:
ReadlineSetup --
http://wiki.python.org/jython/ReadlineSetup.Standalone mode -- You can also create a self-contained Jython jar
file. Run the standard installer (above), then you come to the
"Installation type" page, select "Standalone". For more on this, see:
Standalone mode --
http://www.jython.org/Project/installation.html#standalone-mode2.2 Configuration
There are several places to configure Jython.
2.2.2 Jython configuration files
For explanation of configuration options and values, see:
- The comments in the (default) registry file.
- The Jython Registry --
http://www.jython.org/docs/registry.html.2.2.3 Checking configuration values
From within the Jython interactive interpreter or from within your
Jython application, you can display the values of configuration
properties.To get the system properties as a dictionary-like object, do:
>>> from java.lang import System >>> props = System.getProperties()Of particular interest are the following:
- props['java.class.path'] -- Location of the Jython jar file.
- props['java.library.path'] -- Locations of Java class libraries.
Other properties are in sys.registry:
>>> import sys >>> r = sys.registry >>> for k in r: ... print k, r[k]Here is a script that you may find useful when interactively
inspecting system properties:>>> from java.lang import System >>> props = System.getProperties() >>> names = [] >>> for name in props.keys(): ... names.append(name) ... >>> names.sort() # now you can list the keys in alpha order >>> for val in props['java.class.path'].split(':'): ... print val ... /home/dkuhlman/a1/Python/Jython/Tmp1/Jython-2.1/jython.jar /usr/share/jython/jython.jar2.2.4 Classpath and python path
Jython can pick up Java class files from locations on either the
Jython/Python path (see sys.path) or the Java classpath. Set
these with the following:
The Python/Jython path can be set in your registry file. See
registry variable python.path.Or, at runtime, you could do:
>>> import sys >>> sys.path.append('/path/to/module')But, you must do the above before trying to import the module.
Set the classpath by setting the CLASSPATH environment variable.
Note that (on my Linux machine, at least) the CLASSPATH environment
variable is picked up and added to the Java -classpath flag.A few rules about CLASSPATH and python.path:
- sys.path in the registry file -- Add here to enable importing
from Java classes (.java), Java class libraries (.jar), and
Jython/Python (.py).- CLASSPATH -- Add paths to this environment variable in order to
enable importing from Java classes (.java) and Java class
libraries (.jar), but not Jython/Python (.py).2.3 Running Jython
The Jython interactive, command-line interpreter: jython.
Jython IDEs (interactive development environments) -- There is a
Jython plug-in for Eclipse. See: http://pydev.sourceforge.net/.Exercises -- Start the Jython interpreter. Then do each of the
following:
- Print "hello".
- Define an empty class.
- Import a Python/Jython file containing a class definition.
Create an instance of that class.- Import a module from the standard Python/Jython library, for
example, re or os.path. Use a method from that module.- Import a Java class, for example, java.util.Vector. Create
and use an instance of that class.Running Jython scripts:
From the command line, run a script with jython. For
example:$ jython myscript.pyFor help, run:
$ jython --helpFor debugging, use something similar to the following:
import pdb pdb.run('main()')Or:
import pdb pdb.set_trace()For example:
def main(): util101() if __name__ == '__main__': import pdb; pdb.set_trace() main()To "set a breakpoint" in your code so that it will drop into
debugger, either (1) use the b command at the pdb prompt
or (2) add the following to your code at the location where you
wish to drop into the debugger:import pdb; pdb.set_trace()For more information on the Python debugger, see The Python
Debugger in the
Python standard documentation, or while in the debugger, type
help.To make a script both "run-able" and "import-able", use the
following idiom:if __name__ == '__main__': main()Don't forget to include a doc string at the top of your module for
documentation.Exercise -- Create a small Jython script:
- Include a class in your script that creates an instance of
java.util.Vector.- Make the script both "run-able" and "import-able".
- From the Jython interpreter, import the script and create an instance
of the class.- From the command line, use jython to run the script.
- Add pdb debugging to your script. Run the script again from
the command line. Step through several lines of code.2.4 Installing Jython/Python packages
Some Jython packages will be distributed as a Java jar file. If that
is the case, add the jar file to your classpath.If the package is distributed as a standard Python package with a
setup.py installer file and if there are no C/C++ files in the
package, then you might try something like the following:$ python setup.py install --prefix /path/to/install/directoryAnd, then put that install directory on your classpath.
3 Integrating Java into Jython/Python
3.1 Calling existing Java code
In order to call Java code from Jython do the following:
- Import the Java module.
- Use the Java module to create an instance/object.
- Call functions and objects in it.
It works the way you would hope and expect it to. Here is an
example:>>> from java.util import Vector >>> v = Vector() >>> dir(v) ['__init__', 'add', 'addAll', 'addElement', 'capacity', 'class', 'clear', 'clone', 'contains', 'containsAll', 'copyInto', 'elementAt', 'elements', 'empty', 'ensureCapacity', 'equals', 'firstElement', 'get', 'getClass', 'hashCode', 'indexOf', 'insertElementAt', 'isEmpty', 'iterator', 'lastElement', 'lastIndexOf', 'listIterator', 'notify', 'notifyAll', 'remove', 'removeAll', 'removeAllElements', 'removeElement', 'removeElementAt', 'retainAll', 'set', 'setElementAt', 'setSize', 'size', 'subList', 'toArray', 'toString', 'trimToSize', 'wait'] >>> >>> v.add('aaa') 1 >>> v.add('bbb') 1 >>> for val in v: ... print val ... aaa bbbIn some cases you will need to pass Java objects to Java methods.
Special treatment for some overloaded Java methods -- Explicitly
create and pass Jython objects. For more on this, see:
Overloaded Java Method Signatures
-- http://www.jython.org/Project/userguide.html#overloaded-java-method-signatures.Often you can use Python/Jython style and idioms to process Java
objects. For example: the Jython for statement can be applied
to Java collection objects.Exercise -- Use the class java.util.Hashtable to create a
dictionary with several keys and values, then print out the keys
and their values. Solution:>>> from java.util import Hashtable >>> impl_language = Hashtable() >>> impl_language.put('jython', 'java') >>> impl_language.put('python', 'c') >>> for key in impl_language.keys(): ... print '%s is implemented in %s' % (key, impl_language[key]) ... python is implemented in c jython is implemented in java3.2 Extending a Java class in Jython
You can import and then extend (sub-class) a Java class.
Example -- This sample extends the Java filestream class by adding a
method that converts all characters to upper case::import sys from java.io import FileOutputStream class UppercaseFileOutputStream(FileOutputStream): def write_upper(self, text): text = text.upper() self.write(text) def test(outfilename): fos = UppercaseFileOutputStream(outfilename) for idx in range(10): fos.write_upper('This is line # %d\n' % idx) fos.close() infile = open(outfilename, 'r') for line in infile: line = line.rstrip() print 'Line: %s' % line def main(): args = sys.argv[1:] if len(args) != 1: print 'usage: extend_fileoutputstream.py <infilename>' sys.exit(1) test(args[0]) if __name__ == '__main__': main()3.3 Emulating Jython classes in Java
You can make a Java class "act like" one of the built-in Jython
classes. In order to do so, you would implement one or more of
Jython's special methods. You can find descriptions of the special
methods in the "Python Reference Manual":
3.4 Special method names --
http://docs.python.org/ref/specialnames.html.Example: This module implements a class that acts like a sequence in
certain ways, specifically (1) it responds to the len() operator
by returning a length; (2) it supports an append method; and (3)
it supports the use of the [] operator to get a value:import java.util.Vector;
转载于:https://www.cnblogs.com/lexus/archive/2012/02/28/2372454.html