Can you convert Python to Java?

Can you convert Python to Java? : A portion of Python can be converted into Java using a translator known as P2J . It also translates Python into C , Java, JavaScript, and a number of other languages. My universal-transpiler project was created for the same objective.

Read Detail Answer On Can you convert Python to Java?

You can easily convert python code to Java. In finding a way to convert python code to Java, you come along with many choices but finding the best one that does not affect code’s readability, and speed is essential.

Can I convert Python code to Java? There are several ways for this job. You may use an online converter or install software that can do the job for you.

Some advise using Tokenizer to finish it sooner than you anticipate, or you can also use the Al Code translator. A utility, converter tools, or easy techniques like String Replace Methods are all better ways to complete the task quickly.

Understanding the differences between the utilities and the features and the quality of their work is necessary to choose the best one for yourself.

Al Code Translator

Otherwise, you can implement it in the Google column. Google column is an easier way to do it but doing it in a local system is also always available. By installing all the local dependencies, you can convert your content to Java code.

To implement Transcoder in Google column named notebook, just follow the steps as guided.

  • Check the Python version you are using.
  • According to the transcoder file, we have to install some requirements. So install them one by one.
  • It will show as,

    Similarly, it will ask you to download additional files like Linux files, supporting files, etc. you need to click on them and download them immediately. Just follow the steps, and it will be implemented.

    Using Tokenizer

    The one way is to use the String Replacement Method or the re Regular Expressions to get the exact result.

    The following examplecan explain tokenization.

    Alternate ways

    By utilizing the subsequent application, you can also allow Python-written code to run in Java.

    Jython is a Python interpreter created entirely in Java.

    You can also use an online converter.

    “Python to Java converter online Code Example”

    Various websites will help you convert Python to Java and explain it with comprehensive examples.

    Wrap up

    So, the answer is simply ‘Yes’ to this most asked question “Can I convert Python to java code? All in all, you can make many choices, such as the online convertor,Al translator, Tokenizer, etc., but the best one is that it fulfills your requirements and needs.

    Hence, that is for you to decide among the options what benefits you more and inform us too about it in the comment section.

    Can we convert a Python code to Java online? : There is one tool available by which you can use python code in java application. You can install Jython [^ ]. Then call Python code in Java without converting Python code to Java code.
    How do I convert Java code to Python? : How to Convert Java to Python
    Download and extract java2python.
    Place the contents of the java2python folder on the root of your C:\ drive.
    Open a command prompt and navigate to “C:\java2python” before typing in “python install” without quotes.
    Read Detail Answer On How do I convert Java code to Python?

    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.

    Command line history — On MS Windows, command line history for the Jython interactive interpreter comes built-in. On Linux, to getcommand line history, command line editing, and readline support, follow the instructions here: 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 —

    2.2   Configuration

    There are several places to configure Jython.

    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.jar
    2.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 theJava 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 -classpathflag.

    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:

    Exercises — Start the Jython interpreter. Then do each of the following:

    • Print “hello”.
    • Definean 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
    • For help, run:

      $ jython --help
    • For debugging, use something similar to the following:



      import pdbpdb.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, seeThe 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 ofjava.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 installer file and if there are no C/C++ files in the package, then you might try something like the following:

    $ python install --prefix /path/to/install/directory

    And, then put thatinstall 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 theJava 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...aaabbb

    In 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 htmloverloaded-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 collectionobjects.

    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 cjython is implemented in java

    3.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 classby adding a method that converts all characters to upper case::

    import sysfrom import FileOutputStreamclass 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' % linedef main():    args = sys.argv[1:]    if len(args) != 1:        print 'usage: <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 ReferenceManual”: 3.4 Special method names —

    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;// Implement selected part of the Jython container interface.public class CustomContainer {    private Vector data;    public CustomContainer() {        data = new Vector();    }    // Implement the len() operator.    public int __len__() {        return data.size();    }    // Implement the append() method.    public int append(String item) {        data.add(item);        return 1;    }    // Implement the [] operator.    public String __getitem__(int index) {        return (String)data.elementAt(index);    }}

    And here is an example of the use of thiscustom container class:

    $ jythonJython 2.2.1rc1 on java1.4.2_10Type "copyright", "credits" or "license" for more information.>>>>>> import CustomContainer as cc>>> container = cc()>>> container.append('item number one')1>>> container.append('item number two')1>>> container.append('item number three')1>>> len(container)3>>> for index in range(len(container)):... print container[index]...item number oneitem number twoitem number three


    • A more powerful solution, depending on your needs, would be for CustomContainer to inherit from java.util.Vector. See section Emulating Jython Dictionaries, Sequences, Etc. for an example.

    3.4   Preparing Java code to be called from Jython

    Another view: Java is the extension language for Jython.

    No special work is required. Jython can call normal Java classes.

    Need to pay attention to data types, for example, on the Jython side. Use an explicit cast, for example, float(5).

    For additional help, see:

    • Overview of Jython Documentation
    • The Jython API with frames or without frames.

    You can also customize a Java class to make it more “Jythonic”.

    3.4.1   Adding doc strings to a Java class

    This first, simple example adds doc strings:

    // Showme.javaimport org.python.core.*;public class ShowMe{    public static PyString __doc__ =        new PyString("Simple Jython extension #1");    public String name;    public ShowMe(String newName)    {        name = newName;    }    public static PyString __doc__set_name = new PyString(        "Set the name attribute");    public void set_name(String newName)    {        name = newName;    }    public static PyString __doc__get_name = new PyString(        "Get the name attribute");    public String get_name()    {        return name;    }    public static PyString __doc__Show = new PyString(        "Show the name attribute");    public void Show()    {        System.out.println("My name is \"" + name + "\".");    }}


    • Doc strings for the class and methods are defined with public static Strings. You can, alternatively, use PyString.
    • For more complex control over doc strings (for example, in a Java files that contains multiple classes) your class can implement the ClassDictInitinterface and implement the classDictInit method. See “Jython for Java Programmers”, pp. 276 ff.
    3.4.2   Working with Jython arguments

    The ArgParser class helps us handle Jython keyword arguments. If helps us write Java methods that support the analog of Jython’s *args and **kwargs in Java methods.

    How to do it — An overview:

  • Define your Java method with the following prototype:

    public PyObject foo(PyObject[] args, String[] keywords);
  • Parse the arguments with class ArgParser.
  • Access individual arguments with ArgParser methods getInt(), getString(), getList(), and getPyObject().
  • Since both args and keywords are arrays, check the number of arguments actually passed with args.length and keywords.length.
  • For more information, see: Jython API Documentation: org.python.core Class ArgParser —

    Exercise — (1) Write a Java class containing a method that prints all its arguments and all the keyword arguments passed to it. (2) Then call that method from Jython.


    // DemoArgs.javaimport org.python.core.*;public class DemoArgs{    public static PyString __doc__ =        new PyString("Demonstrate the use of complex arguments.");    public String name;    public String value;    public DemoArgs(String newName, String newValue)    {        name = newName;        value = newValue;    }    public static PyString __doc__set_name = new PyString(        "Set the name attribute");    public void set_name(PyObject[] args, String[] kwargs)    {        System.out.println("length(args): " +            args.length +            " length(kwargs): " +            kwargs.length            );        ArgParser ap = new ArgParser("set_name", args, kwargs,            new String[] {"name", "value"});        String newName = ap.getString(0, "");        String newValue = ap.getString(1, "<empty>");        if (!newName.equals(""))        {            name = newName;        }        value = newValue;    }    public static PyString __doc__get_name = new PyString(        "Get the name attribute");    public String get_name()    {        return name;    }    public static PyString __doc__get_value = new PyString(        "Get the value attribute");    public String get_value()    {        return value;    }    public static PyString __doc__Show = new PyString(        "Show the name and value attributes");    public void Show()    {        System.out.println("My name is \"" + name +            "\" and my value is \"" + value + "\".");    }}

    Compile the above file withjavac or some other Java compiler. To do so, you will need to add jython.jar to your CLASSPATH.


    • Use class ArgParser to capture the arguments.
    • Use ArgParser methods getInt, getString, getPyObject, and getList to retrieve arguments.
    • Notice that in method get_name, we print the length of the args and kwargs. This demonstrates that you can check the length of these arraysand can throw an exception if, for example, too few arguments are passed.

    Also see the Jython FAQ: 5.3 Supporting *args and **kw in Java methods —

    3.4.3   Sub-classinga Java class

    Notice that, in Jython, we can extend a class written in Java:

    import DemoArgsclass Fancy(DemoArgs):    def __init__(self, name, value):        DemoArgs.__init__(self, name, value)    def ShowFancy(self):        print "I'm fancy and my name is %s and my value is %s" % \            (, self.value)def test():    f = Fancy('dave', 'funny')    f.ShowFancy()    f.set_name('daniel', 'cute')    f.ShowFancy()test()

    When you run the above, you should see something like the following:

    $ jython tmp.pyI'm fancy and my name is dave and my value is funnylength(args): 2 length(kwargs): 0I'm fancy and my name is daniel and my value is cute
    3.4.4   Emulating Jython Dictionaries, Sequences, Etc.

    Extend class org.python.core.PyObject and its sub-classes. See:org.python.core Class PyObject.

    Implement the following methods:


    getitem() vs. finditem():

    • If the index is not found or out of range, finditem() returns null, whereas __getitem() should throw an exception.
    • The Jython API documentation says to override finditem() and not getitem(). See:org.python.core Class PyObject.

    See 3 3 5 Emulating container types — http://docs python org/ref/sequence-types html in the Python Reference Manual for more information on customizing dictionaries and sequences

    Exercise — (1) Write a Java class that emulates or imitates a Jython dictionary. (2) Inaddition, each access method should print a message. (3) Test your Java class from Jython by creating an instance of it, then setting and retrieving a key-value pair.   Solution #1 — Emulating a dictionary

    This solution is for educational purposes only (seeSolution #2 — Extending PyDictionary):

    // TestDict.javaimport org.python.core.*;import java.util.*;public class TestDict{ public Hashtable data; public TestDict() {  data = new Hashtable(); } public void __setitem__(String key, String value) {  data.put(key, value);  System.out.println("Added key \"" + key + "\" value: \"" +         value + "\""); } public String __getitem__(String key) {  if (data.containsKey(key))  {   String value = (String)data.get(key);   System.out.println("Found key \"" + key + "\" value: \"" +         value + "\"");   return value;  }  else  {   throw new PyException(Py.KeyError, "The key does not exit.");  } } public boolean __contains__(String key) {  if (data.containsKey(key))  {   System.out.println("Found key \"" + key + "\"");   return true;  }  else  {   System.out.println("Did not find key \"" + key + "\"");   return false;  } }}


    • The above class implements a limited part of the Jython dictionary protocol, in particular __setitem__, __getitem__, and __contains__.

    • This above solution also illustrates how to throw (“raise” in Jython terms) an exception from Java that can be caught in Jython. Here is anexample of catching that exception on the Jython side:

      >>> try:... x = b['xyz']... except KeyError, e:... print '*** error: %s' % e...*** error: The key does not exit.
    • The Jython FAQ recommends that your Jython class extends PyObject. (see 5. Extending Jython — I’ve found that it is not strictly necessary to extend PyObect in your Java class (the one that emulates a Jython built-in). But, if you do, you will need tofollow the signature of the methods that implement operators (for example __setitem__, __getitem__, etc) exactly. To learn those signatures, see the API documentation in the Doc/ directory under your Jython installation.

    Here is an example that uses the above solution:

    # test_TestDict.pyimport TestDictdef test():    d = TestDict()    d['aa'] = 'AAAA'    d['bb'] = 'BBBB'    d['cc'] = 'CCCC'    print    if 'bb' in d:        print 'present'test()

    And, here is the result of running this test:

    $ jython test_TestDict.pyAdded key "aa" value: "AAAA"Added key "bb" value: "BBBB"Added key "cc" value: "CCCC"{aa=AAAA, bb=BBBB, cc=CCCC}Found key "bb"present   Solution #2 — Extending PyDictionary

    This solution shows how you most likely would start if you wanted to extend the dictionary type or implement a custom dictionary type:

    // TestDictSub.javaimport org.python.core.*;import java.util.*;public class TestDictSub extends PyDictionary{    public void __setitem__(PyObject key, PyObject value)    {        super.__setitem__(key, value);        System.out.println("Added key \"" + key + "\" value: \"" +                           value + "\"");    }    public PyObject __getitem__(PyObject key)    {        if (super.__contains__(key))        {            PyObject value = super.__getitem__(key);            System.out.println("Found key \"" + key + "\" value: \"" +                           value + "\"");            return value;        }        else        {            throw new PyException(Py.KeyError, "The key does not exit.");        }    }}


    • This class inherits the methods in the PyDictionary class. It overrides several of those methods, specifically __setitem__ and __getitem__.
    • The Java class couldalso extend the dictionary type by implementing additional, new methods.

    Also see the Jython FAQ: 5.1 Java classes that emulate Jython Dictionaries and Sequences —

    3.4.5   Emulating Jython object attribute access

    We can implement and override object attribute access in a Java class. And, we can emulate other Jython built-in types.

    Extend class org.python.core.PyObject and its sub-classes.

    Implement the following methods, among others:


    __findattr_ex__() is called only if an attribute is not found in an object.

    Exercise– (1) Write a Java class that supports access to attributes. (2) In addition, each access method should print a message. (3) Test your Java class from Jython by creating an instance of it, then setting and getting an attribute.


    // TestAttrAccess.javaimport org.python.core.*;import java.util.*;public class TestAttrAccess extends PyObject{    PyDictionary localdict = new PyDictionary();    public PyObject __findattr_ex__(String name)    {        PyString pyname = new PyString(name);        System.out.println("Finding attr for: \"" + name + "\"");        if (localdict.__contains__(pyname)) {            return localdict.__getitem__(pyname);        }        else        {            return new PyString("[no attr]");        }    }    public void __setattr__(String name, PyObject value)    {        PyString pyname = new PyString(name);        System.out.println("Setting attr for: \"" + name + "\"");        localdict.__setitem__(pyname, value);    }}


    • Test this solution with the following:

      import TestAttrAccessdef test():    a = TestAttrAccess()    a.bbb = 3344    print a.bbb    # Try to access a nonexistent attribute.    print a.ccctest()
    • Arguments to __findattr_ex__ and __finditem__ must be interned strings. Literal strings are automatically interned. For other strings, useintern(s).

    Exercise — (1) Write a Java class that emulates a Jython dictionary, but intercepts key access to items in the dictionary. Print a message when each access is attempted.


    // TestDictSub.javaimport org.python.core.*;import java.util.*;public class TestDictSub extends PyDictionary{    public PyObject __finditem__(PyObject key)    {        System.out.println("Getting item for: \"" + key + "\"");        PyObject objkey = key;        if (super.__contains__(objkey))        {            PyObject value = super.__finditem__(objkey);            System.out.println(  "Found key \"" + key + "\" value: \"" +                value + "\"");            return value;        }        else        {            throw new PyException(Py.KeyError,  "The key does not exit.");        }    }}


    • Here is a test for the above code:

      import TestDictSub as TDSdef test():    a = TDS()    a['aaa'] = 123    a['bbb'] = 456    print a['aaa']    print a['ccc']test()
    • We implement __finditem__() rather than __getitem__(). See the notes for Class PyObject in theJython API documentation —

    Also see the Jython FAQ: 5.2 Emulating Jython object attribute access with a Java class —

    3.6   jarray — Creating and passing Java arrays to Java

    Why you might want to do this — Suppose that you want to pass an array to a Java method. Furthermore, suppose that Java method is going to modify the contents of your array. If you pass in a Jython list, Jython creates a wrapper for your list, and any modifications made by Javawill not be return to Jython.

    In this situation, you will want to use jarray to create Java arrays. For more on Java arrays, see: Jython User Guide: Java Arrays —

    Here is an example of a Java class that modifies the contents of an array. You can use it to demonstrate the need for jarry:

    import java.util.Vector;public class TestJarray { private Integer data[]; public void setdata(Integer newdata[]) {  data = newdata; } public void changedata() throws ArrayIndexOutOfBoundsException {  data[0] = new Integer(99); } public Integer[] getdata() {  return data; }}

    And, here is a Jython program that testsit:

    import jarrayimport java.lang.Integerimport TestJarraydef test():    print '1.', '-' * 30    a1 = TestJarray()    b1 = [11, 22, 33]    a1.setdata(b1)    a1.changedata()    c1 = a1.getdata()    print 'a1:', a1    print 'b1:', b1    print 'c1:', c1    print '2.', '-' * 30    a2 = TestJarray()    b2 = [11, 22, 33]    b2j = jarray.array(b2, java.lang.Integer)    a2.setdata(b2j)    a2.changedata()    c2 = a2.getdata()    print 'a2:', a2    print 'b2:', b2    print 'b2j:', b2j    print 'c2:', c2test()

    This is the output from running the above Jython script:

    $ jython test_jarray.py1. ------------------------------a1: [email protected]: [11, 22, 33]c1: array(java.lang.Integer,[99, 22, 33])2. ------------------------------a2: [email protected]: [11, 22, 33]b2j: array(java.lang.Integer,[99, 22, 33])c2: array(java.lang.Integer,[99, 22, 33])


    • The Jython list (b1) that we pass to Java remains unchanged, because it is “wrapped” by Jython.
    • The jarray (b2j) that we pass to Java is modified.

    Here are a few examples.

    A simple array of ints:

    >>> jarray.array([11, 22, 33], 'i')array('i',[11, 22, 33])

    An array of floats:

    >>> jarray.array([11.0, 22.0, 33.0], 'f')array('f',[11.0, 22.0, 33.0])

    An array of strings:

    >>> jarray.array(['aaa', 'bbb', 'ccc'], java.lang.String)array(java.lang.String,['aaa', 'bbb', 'ccc'])

    The following examples create two-dimensional arrays.

    Anarray of arrays of ints:

    >>> jarray.array([[11, 22], [33, 44]], java.lang.Class.forName("[I"))array([I,[array('i',[11, 22]) , array('i',[33, 44]) ])

    An array of arrays of strings:

    >>> jarray.array([ ['aaa', 'bbb'], ['ccc', 'ddd'] ], java.lang.Class.forName('[Ljava.lang.String;'))array([Ljava.lang.String;,[array(java.lang.String,['aaa', 'bbb']) , array(java.lang.String,['ccc', 'ddd']) ])

    It is also possible to create 3-D arrays — A three dimensional array of ints and another of floats:

    >>> a = [[11, 22], [33, 44]]>>> b = [[55, 66], [77, 88]]>>> c = [a, b]>>> c[[[11, 22], [33, 44]], [[55, 66], [77, 88]]]>>> jarray.array(c, java.lang.Class.forName("[[I"))array([[I,[array([I,[array('i',[11, 22]) , array('i',[33, 44]) ]) , array([I,[array('i',[55, 66]) , array('i',[77, 88]) ]) ])>>> jarray.array(c, java.lang.Class.forName("[[F"))array([[F,[array([F,[array('f',[11.0, 22.0]) , array('f',[33.0, 44.0]) ]) , array([F,[array('f',[55.0, 66.0]) , array('f',[77.0, 88.0]) ]) ])

    Here are a few notes:

    From the language spec, 3rd edition:

    Every array also has a class; the method getClass, when invoked for an array object, will return a class object (of class Class) that represents the class of the array.

    The classes for arrays havestrange names that are not valid identifiers; for example, the class for an array of int components has the name “[I” and so the value of the expression:


    is the string “[I”; see the specification of Class.getName for details.

    From API spec for Class.getName:

    If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more'[‘ characters representing the depth of the array nesting. The encoding of element type names is as follows:

    Element Type Encodingboolean Zbyte Bchar Cclass or interface Lclassname;double Dfloat Fint Ilong Jshort S

    The class or interface name classname is the binary name of the class specified above.


    • Jython User Guide: Java Arrays —
    • The Java Language Specification, Third Edition: Types, Values, and Variables —
    • Java Platform, Standard Edition 6 API Specification —

    4   Integrating Jython/Python into Java

    4.1   Calling Jython from Java

    4.1.1   Run Jython code on aninterpreter embedded in Java

    jythonc is currently unsupported and is deprecated, although it might reappear in some future version of Jython. So, using jythonc to compile your Jython code to Java for use in your Java code may not appeal to you. An embedded Jython interpreter may be a solution.

    Overview — Here is the general approach:

  • Create a Jython interpreter object.
  • Insert (set) values in your embedded interpreter, if needed.
  • Usethat interpreter to either:

  • Run several lines of code that import and use your Jython module, or
  • Run a small wrapper script that imports and uses your Jython modules.
  • Retrieve values from your embedded interpreter, if necessary.
  • READ More:  Camera Obscura On Steam Free Download Full Version

    Each of these topics has been covered above.

    Disadvantages of this approach:

    • It’s a little clumsy. Requires a small amount of Java code.

    Advantages of this approach:

    • jythoncis not required. jythonc is deprecated and is not planned for Jython 2.3.
    • No need for a separate compile step.
    • No need to re-compile your script each time it is modified.
    4.1.2   How to run Jython code on an interpreter embedded in Java

    Resources — For instructions on how tocall Jython code from Java, see:

    • Accessing Jython from Java Without Using jythonc
    • Simple and Efficient Jython Object Factories — Note that thefollowing examples were developed from this document.

    Description — In order to implement this approach, here is what you will do:

    • Implement one or more Jython/Python modules containing one or more classes. Or, perhaps this code already exists.
    • Create a Java interface for each Jython class that you want to expose to Java. The interface should describe each method that you wish to expose to Java.
    • Create a single Java “factory” class:
      • The constructor(1) creates a Jython interpreter; (2) runs a script that imports the Jython modules containing the Jython classes; (3) retrieves and saves the Jython classes from the intrepreter.
      • Implement one “createX” method for each Jython/Python class/type to be used from Java.
    • Implement the Java code that uses the Jython classes. This Java code will typically do the following:
    • Create a factory object.
    • Call the “createX” methods to create Java objects that giveaccess to the Jython classes.
    • Call the Jython methods through these Jython “proxies”.   Example — the Jython classes

    These are the Jython classes that we wish to expose to and call from Java:

    # Employee.pyfrom jyinterface.interfaces import EmployeeTypefrom jyinterface.interfaces import DependentTypeclass Employee(EmployeeType):    def __init__(self, first, last, id):        self.first = first        self.last = last = id        deps = self.create_dependents()        self.deps = deps    def create_dependents(self):        d1 = Dependent('Sally', 'Serious', 11)        d2 = Dependent('Larry', 'Lighthearted', 12)        return [d1, d2]    def getEmployeeFirst(self):        return self.first    def getEmployeeLast(self):        return self.last    def getEmployeeId(self):        return    def getDependents(self):        return self.deps    def addDependent(self, dependent):        self.deps.append(dependent)class Dependent(DependentType):    def __init__(self, first, last, id):        self.first = first        self.last = last = id    def getDependentFirst(self):        return '<<%s>>' % self.first    def getDependentLast(self):        return '<<%s>>' % self.last    def getDependentId(self):        return * 4   Example — A Java interface class

    This (jyinterface/interfaces/ describes the interface to our Java (client) code:

    // EmployeeType.javapackage jyinterface.interfaces;import org.python.core.PyList;import jyinterface.interfaces.DependentType;public interface EmployeeType {    public String getEmployeeFirst();    public String getEmployeeLast();    public String getEmployeeId();    public PyList getDependents();    public void addDependent(DependentType dependent);}   Example — another interface class

    This(jyinterface/interfaces/ is another interface. It describes and helps to expose another Jython class.

    // DependentType.javapackage jyinterface.interfaces;public interface DependentType {     public String getDependentFirst();     public String getDependentLast();     public Integer getDependentId();}


    • We only describe the portions of the interface that we wish to expose to Java. It is likely that this will be a proper subset of the methods in our Jython class.   Example — the factoryclass

    This (jyinterface/factories/ is the factory that creates (proxy) instances of our Jython classes. These instances are Java instances with an underlying Jython implementation:

    // EmployeeFactory.javapackage jyinterface.factory;import jyinterface.interfaces.EmployeeType;import jyinterface.interfaces.DependentType;import org.python.core.PyObject;import org.python.core.PyString;import org.python.core.PyInteger;import org.python.util.PythonInterpreter;public class EmployeeFactory {    public EmployeeFactory() {        String cmd = "from Employee import Employee\nfrom Employee import Dependent";        PythonInterpreter interpreter = new PythonInterpreter();        //interpreter.exec("from Employee import Employee");        //interpreter.exec("from Employee import Dependent");        interpreter.exec(cmd);        jyEmployeeClass = interpreter.get("Employee");        jyDependentClass = interpreter.get("Dependent");    }    public EmployeeType createEmployee(String first, String last, String id) {        PyObject employeeObj = jyEmployeeClass.__call__(            new PyString(first),            new PyString(last),            new PyString(id));        return (EmployeeType)employeeObj.__tojava__(EmployeeType.class);    }    public DependentType createDependent(String first, String last, int id) {        PyObject dependentObj = jyDependentClass.__call__(            new PyString(first),            new PyString(last),            new PyInteger(id));        return (DependentType)dependentObj.__tojava__(DependentType.class);    }    private PyObject jyEmployeeClass;    private PyObject jyDependentClass;}


    • The Jython interpreter is created only once, when the factory object is created.
    • The Java classes that are proxies for the Jython classes exposed to Java (jyEmployeeClass amd jyDependentClass) are also only created once.
    • Each “creater”method (createEmployee and createDependent) uses the __call__ method to create an instance. This is the same as using obj = Employee(), for example, in Jython. Then the result is converted to a Java object and returned.   Example — the Java consumer code

    This (jyinterface/ is the Java code that usesour Jython classes:

    // Main.javapackage jyinterface;import jyinterface.factories.EmployeeFactory;import jyinterface.interfaces.EmployeeType;import jyinterface.interfaces.DependentType;import org.python.core.PyObject;import org.python.core.PyList;public class Main {    private static void printEmployee(EmployeeType employee) {        System.out.println("Name: " + employee.getEmployeeFirst() + " "                + employee.getEmployeeLast());        System.out.println("Id: " + employee.getEmployeeId());        PyList deplist = employee.getDependents();        int count = deplist.__len__();        System.out.println("count: " + count);        for (int idx = 0; idx < count; idx++) {            PyObject obj = deplist.__getitem__(idx);            DependentType dep = (DependentType)obj.__tojava__(DependentType.class);            printDependent(dep);        }    }    private static void printDependent(DependentType dependent) {        System.out.println("Dep Name: " + dependent.getDependentFirst() + " "                + dependent.getDependentLast());        System.out.println("Dep Id: " + dependent.getDependentId());    }    public static void main(String[] args) {        EmployeeFactory factory = new EmployeeFactory();        EmployeeType emp = factory.createEmployee("Josh", "Juneau", "1");        printEmployee(emp);        printEmployee(factory.createEmployee("Charlie", "Groves", "2"));        System.out.println("------------------");        DependentType dependent = factory.createDependent(            "Dave", "Kuhlman", 4);        printDependent(dependent);        System.out.println("------------------");        emp.addDependent(dependent);        printEmployee(emp);    }}


    • This client code creates a factory object, then uses that factory object to create several Java objects that are proxies for the Jython Employee and Dependent objects.

    • Then the client code calls several of the methods that are implemented in the Jython code and exposed to Java through the Java interfaces.

    • On the Java side, we apply operators to a list object (and other Jython built-in types) by calling theirmethods directly, for example:

      • len() — obj.__len__()
      • obj[idx] — obj.__getitem__(idx)

      For descriptions of these “special” methods, see the following section in the Python language reference: 3.4 Special method names —

    • On the Java side, we use a Jython object by

    • Retrieving it as ageneric PyObject.

    • Converting it to a Java object with:


      where XXType is the Java interface that describes the Jython object.

    • Casting the object to the appropriate Java type.

    • Calling its “Java” methods.

    • We can pass a Jython object back to Jython from Java. Notice the call to method addDependent().

    4.2   Embedding Jython into Java

    4.2.1   Why embedded Jython

    There are several reasons and purposes for embedding the Jython interpreter into your Java application:

    • You want to offer your users the flexibility and power of customizing and extending yourapplication. An embedded Jython interpreter enables them to run Jython scripts in your application and to communicate with it.
    • You have existing Jython code, and you want to use that code in your Java application. Note that this is a capability that might have been handled by using the jythonc compiler to compile your Jython script into Java code, but jythonc is deprecated. For an example of this technique and information on how to do it, see section Calling Jython from Java.

    Also see: Jython User Guide: Embedding Jython –

    4.2.2   Embedding Jython intoJava is simple

    Embedding the Jython interpreter can be as simple as this:

    // File: SimpleEmbedded.javaimport org.python.util.PythonInterpreter;import org.python.core.*;import*;public class SimpleEmbedded{    public static void main(String[]args) throws PyException, IOException    {        BufferedReader terminal;        PythonInterpreter interp;        terminal = new BufferedReader(new InputStreamReader(;        System.out.println ("Hello");        interp = new PythonInterpreter();        interp.exec("import sys");        interp.exec("print sys");        interp.set("a", new PyInteger(42));        interp.exec("print a");        interp.exec("x = 2+2");        PyObject x = interp.get("x");        System.out.println("x: " + x);        PyObject localvars = interp.getLocals();        interp.set("localvars", localvars);        String codeString = "";        String prompt = ">> ";        while (true)        {            System.out.print (prompt);            try            {                codeString = terminal.readLine();                if (codeString.equals("exit"))                {                    System.exit(0);                    break;                }                interp.exec(codeString);            }            catch (IOException e)            {                e.printStackTrace();            }        }        System.out.println("Goodbye");    }}
    4.2.3   Passing values into a Jython script

    Notice the call interp.set(“a”, new PyInteger (42)); in the above example.

    You can also retrieve the dictionary object representing the namespace for the interpreter, then retrieveobjects from that dictionary. Example:

    PyDictionary namespace = interp.getLocals();PyObject obj = namespace.__getitem__("x");Integer x = obj.__tojava__(Integer.class);
    4.2.4   Initializing the interpreter

    You can also create a Jython interpreter with an initial global namespace:

    // File: TestInterp01.javaimport org.python.util.PythonInterpreter;import org.python.core.*;import*;public class TestInterp01{    public static void main(String[]args) throws PyException, IOException    {        PythonInterpreter interp;        PyString key;        PyInteger value;        System.out.println ("Hello");        PyDictionary table = new PyDictionary();        key = new PyString("aaa");        value = new PyInteger(111);        table.__setitem__(key, value);        key = new PyString("bbb");        value = new PyInteger(222);        table.__setitem__(key, value);        interp = new PythonInterpreter(table);        interp.exec("print 'aaa:', aaa");        interp.exec("print 'bbb:', bbb");    }}   An interpreterwith an initial system state

    And, you can create an interpreter with an initial system state:

    // File: TestInterp02.javaimport org.python.util.PythonInterpreter;import org.python.core.*;import*;public class TestInterp02{    public static void main(String[]args) throws PyException, IOException    {        PythonInterpreter interp;        PyString key;        PyInteger value;        System.out.println ("Hello");        PyDictionary table = new PyDictionary();        key = new PyString("aaa");        value = new PyInteger(111);        table.__setitem__(key, value);        key = new PyString("bbb");        value = new PyInteger(222);        table.__setitem__(key, value);        PySystemState state = new PySystemState();        interp = new PythonInterpreter(table, state);        interp.exec("print 'aaa:', aaa");        interp.exec("print 'bbb:', bbb");    }}   A system state and a custom class loader

    This is of interest because the system state can be used to provide a custom class loader:

    PyDictionary table = new PyDictionary();RestrictedClassLoader classLoader = new RestrictedClassLoader();PySystemState state = new PySystemState();state.setClassLoader(classLoader);PythonInterpreter interp = new PythonInterpreter(table, state);

    And here is a sample class loader. This one merely restricts theclasses that can be loaded to a small set:

    // RestrictedClassLoader.javaimport java.util.ArrayList;class RestrictedClassLoader extends ClassLoader {    ArrayList<String> goodnames;    public RestrictedClassLoader () {        goodnames = new Vector();        goodnames.add("Goodclass1");        goodnames.add("Goodclass2");        goodnames.add("Goodclass3");        goodnames.add("Goodclass4");    }    public Class findClass(String name) throws ClassNotFoundException {        for (String item : goodnames)        {            if (item.equals(name))            {                return super.findClass(name);            }        }        throw new ClassNotFoundException("class loading restricted. " +            name + " not allowed.");    }}
    4.2.5   Retrieving values from a Jython script

    Notice the call PyObject x = interp.get(“x”); in the above example.

    You can also retrieve the dictionary object representing the namespace for the interpreter, then add and modify the names and their values in thatdictionary. Example:

    PyDictionary namespace = interp.getLocals();PyInteger value = new PyInteger(144);namespace.__setitem__("x", value);
    4.2.6   There are also a few complexities

    You will want to selectively expose capabilities from your Java application to scripts run by/on the embedded Jython interpreter.

    You will want to protect your application from malicious or erroneous scripts.

    Here are a few suggestions:

    • Describeyour possible classes of users (those who will write scripts) with respect to (1) trusted vs. untrusted and (2) error tolerant vs. non-tolerant.
    • For users who are trusted and error tolerant, provide transparent objects from your application.
    • For users who are trusted and not error tolerant, provide opaque objects, i.e. wrappers for real objects from your application.
    • For users who are not trusted, implement a security policy, or do not expose a scriptinginterface at all.
    4.2.7   Exposing transparent objects

    Java application objects and values can be passed through to scripts executed or evaluated by the embedded interpreter.

    Some mechanisms for passing objects:

    • set and get — Use these to set or retrieve values in the local namespace for the scriptsthat your embedded interpreter will run or has run.
    • setLocals and getLocals — Using these methods, you can pass or retrieve the entire namespace. If you are inserting values to be used (or shared) by scripts, you may want to retrieve and, possibly, copy the initial namespace. Remember that is a Jython dictionary, so modifying it without copying may affect other scripts running in the same interpreter.
    4.2.8   Exposing opaque objects

    This is similar to the strategy for transparent objects, except that you must implement wrapper classes, then provide instances of these classes instead of instances of transparent objects.

    4.2.9   Type conversion

    Mostly,Jython takes care of this for you.

    However, at times it may help to know what conversions are performed.

    And, you can also perform explicit conversions.

    4.2.11   Embedding a Jython console

    This example shows how to embed a Jython interactive console into a Java program:

    import org.python.util.InteractiveConsole;import java.util.Properties;import*;public class interactive_console1 {    protected InteractiveConsole interp;    public interactive_console1() {        if (System.getProperty("python.home") == null) {            System.setProperty("python.home", "");        }        InteractiveConsole.initialize(System.getProperties(),                                      null, new String[0]);        interp = new InteractiveConsole();    }    public static void main(String[] args) {        interactive_console1 con = new interactive_console1();        con.startConsole();    }    public void startConsole() {        interp.interact("Hello from console.");    }}


    • For more information see:API information on Class InteractiveConsole —

    4.3   Embedding Jython with the Java Scripting Engine

    A scripting engine is an alternative wayto execute Jython scripts from within Java.

    4.3.2   Using script engine support

    Here is a simple example that (1) displays information about existing script engines and (2) runs several lines of Jython code:

    // File: ScriptEngine1.javaimport*;import java.util.*;import javax.script.ScriptEngineManager;import javax.script.ScriptEngineFactory;import javax.script.ScriptEngine;import javax.script.ScriptException;public class ScriptEngine1{    public static void main(String[]args) throws IOException, ScriptException    {        listEngines(); // Note 1        ScriptEngineManager mgr = new ScriptEngineManager(); // Note 2        ScriptEngine eng = mgr.getEngineByName("python");        System.out.println("eng: " + String.valueOf(eng));        eng.put("var1", new Integer(257)); // Note 3        eng.eval("print 'var1: %s' % var1");        eng.eval("import sys"); // Note 4        eng.eval("print sys.version");    }    public static void listEngines(){ // Note 1        ScriptEngineManager mgr = new ScriptEngineManager();        List<ScriptEngineFactory> factories =                mgr.getEngineFactories();        for (ScriptEngineFactory factory: factories) {            System.out.println("ScriptEngineFactory Info");            String engName = factory.getEngineName();            String engVersion = factory.getEngineVersion();            String langName = factory.getLanguageName();            String langVersion = factory.getLanguageVersion();            System.out.println("\tScript Engine: " + engName + ":" +                               engVersion);            List<String> engNames = factory.getNames();            for(String name: engNames) {                System.out.println("\tEngine Alias: " + name);            }            System.out.println("\tLanguage: " + langName + ":" +                               langVersion);        }    }}


  • Funtion listEngines iterates over each of the available script engines and prints out a bit ofinformation about each one.
  • We retrieve the Jython script engine.
  • From Java, we set a variable in the engine/Jython environment, then evaluate a Jython script that prints the value of the variable.
  • We evaluate several lines of code that import the sys module and displays the Jython version number.
  • This is the result of running the above Java program:

    $ javac$ java ScriptEngine1ScriptEngineFactory Info        Script Engine: jython:2.2b1        Engine Alias: jython        Engine Alias: python        Language: python:2.2b1ScriptEngineFactory Info        Script Engine: Mozilla Rhino:1.6 release 2        Engine Alias: js        Engine Alias: rhino        Engine Alias: JavaScript        Engine Alias: javascript        Engine Alias: ECMAScript        Engine Alias: ecmascript        Language: ECMAScript:1.6eng: [email protected]: 2572.2.1

    4.4   Compiling Jython code with jythonc

    4.4.1   Introduction to jythonc

    jythonc is currently unsupported and is deprecated, although it might reappear in some future version of Jython. Here is a message on this from the jython-users email list:

    Subject: Re: [Jython-users] What will replace jythonc in 2.3Date: Thu, 29 Nov 2007 09:29:10 -0500From [email protected] Thu Nov 29 06:29:17 2007From: "Frank Wierzbicki" <[email protected]>To: "Chris Fenton" <[email protected]>Cc: [email protected] Nov 29, 2007 8:23 AM, Chris Fenton <[email protected]> wrote:> I use jythonc regularly to distribute webstart apps for my fellow> biologists.> If jythonc disappears what is the obvious replacement for generating jars.The next Jython is some way off -- but we are aware that there are anumber of use cases that need to be covered one way or another whenthe old jythonc disappears. Some of them won't require a jythonc atall -- I suspect that we can come up with a reasonable jarringstrategy w/o jythonc. I think we will find that some of the use casesare best served by a new version of jythonc -- but one that will bebased on the same code as the "regular" compiler. This is all tbdthough -- first we have to get our 2.5 features straightened out onthe basic compiler.-Frank

    What jythonc does:

    • Generates Java code from a Jython class.
    • Compiles the generated Java code.
    • Packages the compiled Java code in a jar file.

    What jythonc is (sometimes) used for:

    • To generate Java code so that classes written in Jython can be used from Java. But, see section Calling Jython from Java for an alternativetechnique.
    • To package an application in a jar file for deployment. But, see section Deployment and Distribution for an alternative technique.
    4.4.2   How to run jythonc

    Here are examples.

    Create a self-contained jar file withjythonc:

    $ jythonc -j hello.jar -a

    Create java class files that can be imported into Java:

    $ jythonc hello.jar
    4.4.3   Calling Jython from Java using jythonc

    Preparing Jython code for jythonc — Create Java compatible Jython modules:

    • The Jython class must inherit from a Java class.
    • The name of the Jython module and theclass in it must be the same. For example, class Foo must be in a module named
    • Add @sig directives to methods that you want to be able to call from Java.

    Another view: Jython is the extension language for Java.

    What is jythonc and what is its status?

    “jythonc transforms Python source code into Java source code then invokes a Java compiler to turn it into .class files. This allows Python to be integrated intoJava in several places that regular Jython currently doesn’t support. It also processes special annotations in docstrings on methods in Python code to determine the static type information to expose when turning a dynmically typed Python method into a statically typed Java method.

    “jythonc is unmaintained and will not be present in Jython-2.3. While jythonc handles all of the language features present in Jython 2.2, it doesn’t support 2.3 features such as generators. As such, it is notrecommended that new Jython projects make use of jythonc. It is only included in Jython-2.2 to support older users of jythonc and to allow access to a few features that are only provided by jythonc at the moment:

  • Running in a JVM with a classloader that will not load dynamically created classes
  • Declaring Java method signatures in Python code
  • Loading Python classes dynamically from Java with Class.forName
  • “While all of these features are planned forJython-2.3, they are currently only available from jythonc. Most uses of the second feature, adding method declarations to docstrings, can be handled by declaring a Java interface to implement with a Python class. Each method in the Python implementation takes the types of the Java method it implements. Exposing the Python class as an instance of that type to Java code can be done as explained in Accessing Jython from Java Without Using jythonc and its followup, Simple and Efficient JythonObject Factories.”


    You can extend Java classes in your Jython code.

    You can add (J)Python protocols to Java classes.

    You will need to describe the signature of methods in order to make them callable from Java (in addition to Jython).

    What jythonc does — jythonc translates .py files source code files, then compiles these to .class files.

    With jythonc, you can also:

    • Compile Jython (.py) to Java class files (.class).

    • Compile Jython to Java source, then stop without compiling to .class files.

    • Create standalone jar file containing your Jython code and that can be run on machines on which Java is installed but not Jython.

    • Use a Java compiler different from the default:javac. See the help from jythonc:

      --compiler path-C path    Use a different compiler than `standard' javac. If this is set to    `NONE' then compile ends with .java. Alternatively, you can set the    property python.jpythonc.compiler in the registry.

      This option can also be set in your Jython registry file.

    Java compatible classes – In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

    • Inherit from a Java class or interface.
    • Include only one class per module.
    • Give the Jython class and the source file that contains it thesame name.
    • Place all code inside that Jython class.
    • Include method signature hints (called sig-strings) — Add a @sig line in the doc-string for each method.

    How to use jythonc:

    • Type jythonc –help for help:

      $ jythonc --help
    • Compile your Jython code with:


    Some notes:

    • When your run jythonc, by default, the .java files are placed in a sub-directory ./jpywork. You canoverride this with the –workdir command line option. From jythonc –help:

      --workdir directory-w directory    Specify working directory for compiler (default is ./jpywork)
    • When you run this resulting code from Java, the directory ./jpywork and the Jython jar file must be on your classpath.

    Example — The following Jython code extends a Java class. Compile it with jythonc:

    # Foo.pyimport javaclass Foo(java.util.Date):    def __init__(self):        self.count = 0    def bar(self, incr=1):        """@sig void bar(int incr)"""        self.count += incr        return self.count    def toString(self):        cnt =        return "Foo[" + java.util.Date.toString(self) + " " + `cnt` + "]"

    Example, continued — Here is Java code to test the above. Compile it with javac and run it:

    // FooTest.javapublic class FooTest {     public static void main(String[] args) {         Foo foo = new Foo();         System.out.println(foo);;;         System.out.println(foo);     }}


    • You will need to add jpywork on your classpath. So, you can compile and run it as follows:

      $ jythonc$ javac -cp jpywork:$CLASSPATH$ java -cp jpywork:$CLASSPATH FooTest

    In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

    • Inherit from a Java class or interface. If you do not need to inherit any additional capability, inherit from java.lang.Object.
    • Include method signature hints (calledsig-strings).
    • Give the Jython class and the source file it is in the same name.

    Here is another simple example:

    """simpleclass.pyThis is a simple class to demonstrate the use of jythonc."""import java.lang.Objectclass simpleclass(java.lang.Object):    def __init__(self, name='The Horse With No Name'): """public simpleclass(String name) """ = name self.size = -1    def set_name(self, name):        """@sig public void set_name(String name)        """ = name    def set_size(self, size):        """@sig public void set_size(int size)        """        self.size = size    def show(self):        """@sig public String show()        """        return 'name: %s size: %s' % (, self.size, )def test():    sc = simpleclass()    s1 =    print "1.", s1    sc.set_name("dave")    sc.set_size(4321)    s1 =    print "2.", s1if __name__ == '__main__':    test()

    And, a Java test harness for this simple example:

    // simpleclasstest.javapublic class simpleclasstest {    public static void main(String[] args) {        String s1;        simpleclass sc = new simpleclass();        s1 =;        System.out.println("1. " + s1);        sc.set_name("dave");        sc.set_size(4321);        s1 =;        System.out.println("2. " + s1);    }}


    • Compile and run with something like the following:

      $ jythonc$ javac -cp jpywork:$CLASSPATH$ java -cp jpywork:$CLASSPATH simpleclasstest1. name: The Horse With No Name size: -12. name: dave size: 4321
    • You will need to put jpywork on your CLASSPATH.

    • In order to produce a Java compatible class, our Jython class must inherit from a Java class. In this case, we usejava.lang.Object, because we do not need to inherit any behavior.

    • The methods set_name, set_size, and show each have sig-strings.

    In the following example, we create a stand-alone Jar file, that is, one that can be executed as a script on a machine where Jython is not installed. Here is the Jython script:

    # test_jythonc.pyimport sysdef test(words):    msgs = ['hi', 'bye']    for word in words:        msgs.append(word)    for msg in msgs:        print msgdef main():    args = sys.argv[1:]    test(args)if __name__ == '__main__':    main()

    Compile and build a Jar file with the following:

    $ jythonc --all --jar mytest.jar

    Run it as follows:

    $ java -jar mytest.jar hello goodbyehibyehellogoodbye


    • Notethat our Jython script contains no class. jythonc will create a public class and a public static main function for us.
    • The –jar flag tells jythonc that we want the results placed in a Jar file (as opposed to placing it in the work directory ./jpywork).
    • The –all flag tells jythonc to include all Jython support in the Jar file, making it stand-alone. This enables us to run it on a system where Java is installed but Jython isnot.

    And the following example builds a standalone jar file from our module, above:

    $ jythonc -j simpleclass.jar -a$ java -jar simpleclass.jar1. name: The Horse With No Name size: -12. name: dave size: 4321

    5   Deployment and Distribution

    Suppose we would like to package our Jython application in a Java jar file, then deploy our application by distributing that jar file so that our users can run it. And,furthermore, suppose we would like our users to be able to run our Jython application on machines where Jython is not installed.

    This section explains how to do that. This explanation is also at: Distributing Jython Scripts —

    So, this boils down to:

    • Having your scripts (*.py) insidestandalone jython.jar in the /lib directory

    • Having all the classes (*.class) in the /org or /com directory

    • Having all the jar files you need on the classpath (including standalone jython.jar)

    • Start java with the -jar option. For example:

      $ java -jar jython.jar {optional .py file}

    5.1   Building jars – somesamples

    The following examples assume that you want to build and run your Jython application from a jar file in a way that is ”’not”’ dependent on files in your Jython installation. This will enable your users to run your Jython application (packaged in a jar file) without installing Jython. They will, of course, need Java installed on their machines.

    The following example scripts were developed on Linux (and the bash shell), but with minor modifications, you should be able todo the same thing in an MS DOS box on MS Windows. I use the zip/unzip tools available from Info-Zip (, but other tools that support the zip format should also work.

    5.1.1   Add Jython install stuff to our jar

    To build our jar, we first make a copy of jython.jar,then add the contents of the Lib/ directory to it:

    $ cd $JYTHON_HOME$ cp jython.jar jythonlib.jar$ zip -r jythonlib.jar Lib

    Note also that the Jython installer enables you to create a stand-alone jar file.

    5.1.2   Add modules and paths to the jar file

    Then we copy this expanded jar file, and add modules that are specific to our application. I’m also going to add a path to anadditional jar file to the manifest:

    $ cd $MY_APP_DIRECTORY$ cp $JYTHON_HOME/jythonlib.jar myapp.jar$ zip myapp.jar Lib/ Add path to additional jar file.$ jar ufm myapp.jar

    Where, contains the following:

    Class-Path: ./otherjar.jar
    5.1.3   Run the script/jar

    Now I have a self-contained jar file that I can run by executing the following:

    $ java -jar myapp.jar

    The file imports modules that I have added to myapp.jar and otherjar.jar, then starts myapplication.

    5.1.4   A more self-contained jar file

    Now suppose you want to package your “start-up” script in the (main) jar itself. In order to do so, follow the above instructions plus:

    • Rename (or copy) your start-up script to Add it to the (main) jar file at the root. (On Linux/UNIX you could also dothis by using the ln -s command to create a symbolic link.) For example, you might do something like this:

      $ zip myapp.jar
    • Add the path to your jar to your CLASSPATH environment variable.

    Now you can run your application with the following:

    $ java org.python.util.jython -jar myapp.jar

    Notice how, when we start the application, we specify the jython class (org.python.util.jython) on the command line. That starts the Jython interpreter, which looks for and runs our __run__.pyscript.

    Alternatively, instead of adding your standalone jar to the CLASSPATH environment variable, you can use the -cp or -classpath command line options:

    $ java -cp myapp.jar org.python.util.jython -jar myapp.jar

    And, a shorter form which does the same thing is this:

    $ java -jar myapp.jar -jar myapp.jar

    This works because Java and Jython both have -jar options. The first -jar tells Java to run Jython, and the second -jar tells Jython to run the in the jar file.

    5.1.5   A summary

    Create the basic jar:

    $ cd $JYTHON_HOME$ cp jython.jar jythonlib.jar$ zip -r jythonlib.jar Lib

    Add other modules to the jar:

    $ cd $MY_APP_DIRECTORY$ cp $JYTHON_HOME/jythonlib.jar myapp.jar$ zip myapp.jar Lib/ Add path to additional jar file.$ jar ufm myapp.jar

    For a more self-contained jar, add the module:

    # Copy or rename your start-up script.$ cp Add your start-up script ( ot the jar.$ zip myapp.jar Add path to main jar to the CLASSPATH environment variable.$ export CLASSPATH=/path/to/my/app/myapp.jar:$CLASSPATH

    On MS Windows, that last line, setting the CLASSPATH environment variable, would look something like this:

    set CLASSPATH=C:\path\to\my\app\myapp.jar;%CLASSPATH%

    Or, again on MS Windows, use the Control Panel and the System propertiesto set the CLASSPATH environment variable.

    Run the application:

    $ java -jar myapp.jar arg1 arg2

    Or, if you have added your start-up script to the jar, use one of the following:

    $ java org.python.util.jython -jar myapp.jar arg1 arg2
    $ java -cp myapp.jar org.python.util.jython -jar myapp.jar arg1 arg2
    $ java -jar myapp.jar -jar myapp.jar arg1 arg2

    6   Integrating, Embedding, and Extending — A Summary

    Here is what we have learned to do:

    • Import and use Java classesin Jython.
    • Extend a Java class in Jython.
    • Implement Java classes that are more “Jythonic” and that expose Jython features such as doc-strings, inherit and extend Jython classes (for example, PyList, PyDict, etc.).
    • Call Jython code from Java.
    • Embed a Jython interpreter in a Java application.
    • Package and deploy a Jython application as a jar file.

    7   Jython+Java — Other Advanced Topics

    7.1   Event handling

    Events are easy in Jython.

    Here is an example taken from “An Introduction to Jython” (

    from javax.swing import *def hello(event):    print "Hello. I'm an event."def test():    frame = JFrame("Hello Jython")    button = JButton("Hello", actionPerformed = hello)    frame.add(button)    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)    frame.setSize(300, 300)

    7.2   XML

    7.2.1   jaxp

    Note: Tested with jython-2.2a.


    """To run this example, set your CLASSPATH with something like the following:    export CLASSPATH=\    ${path-to-xerces}/xerces-2_8_0/xercesImpl.jar:\    ${path-to-xerces}/xerces-2_8_0/xml-apis.jar"""import sysimport java.lang.Booleanfrom javax.xml.parsers import DocumentBuilderFactorydef test(infilename):    """Parse XML document and show attributes and names.    """    dbf = DocumentBuilderFactory.newInstance()    t = java.lang.Boolean(1)    dbf.setNamespaceAware(t)    db = dbf.newDocumentBuilder();    doc = db.parse(infilename)    # print dir(doc)    node = doc.getDocumentElement()    print 'Attributes:'    show_attrs(node)    print 'Names:'    show_names(node)def show_attrs(node):    """Show the attributes and their values.    """    node = node.getFirstChild()    while node:        if node.getNodeType() == node.ELEMENT_NODE:            print ' %s:' % (node.getTagName(), )            attrs = node.getAttributes()            count = attrs.getLength()            for idx in range(count):                attr = attrs.item(idx)                print ' %s: %s' % (                    attr.getNodeName(), attr.getNodeValue(), )        node = node.getNextSibling()def show_names(node):    """Show the value of the name element for each person element.    """    node = node.getFirstChild()    while node:        if (node.getNodeType() == node.ELEMENT_NODE and            node.getTagName() == 'person'):                show_person_name(node)        node = node.getNextSibling()def show_person_name(node):    node = node.getFirstChild()    while node:        if (node.getNodeType() == node.ELEMENT_NODE and            node.getTagName() == 'name'):                show_text('name: ', node)        node = node.getNextSibling()def show_text(msg, node):    """Show a message and the value of a text node.    """    node = node.getFirstChild()    while node:        if node.getNodeType() == node.TEXT_NODE:            print ' %s %s' % (msg, node.getNodeValue(), )        node = node.getNextSibling()def usage():    print 'Usage: jython <infilename>'    sys.exit(-1)def main():    args = sys.argv[1:]    if len(args) != 1:        usage()    test(args[0])if __name__ == '__main__':    main()


    • jaxp: JAXP Reference Implementation(
    • Java API for XML Processing (JAXP) (
    READ More:  Shinobi Bad Buddies On Steam Free Download Full Version
    7.2.2   Xerces

    Xerces is animplementation of XML parsers and a lot more. The JAXP API is also implemented in Xerces2.

    Obtain Xerces here:

    Installation instructions are here: Installation Instructions.

    Set-up — Set your CLASSPATH. After unpacking the Xerces distribution, add the following jar files toyour CLASSPATH:

    • xercesImpl.jar
    • xml-apis.jar

    Here is an example that uses the Xerces DOM parser to parse an XML document, then print out information about the top level nodes in the document:

    from org.apache.xerces.parsers import DOMParser as dpdef test():    parser = dp()    parser.parse('people.xml')    doc = parser.getDocument()    node = doc.getFirstChild()    node = node.getFirstChild()    while node:        if node.getNodeType() == node.ELEMENT_NODE:            print node.getTagName()            attrs = node.getAttributes()            count = attrs.getLength()            for idx in range(count):                attr = attrs.item(idx)                print ' %s: %s' % (attr.getNodeName(), attr.getNodeValue(),)        node = node.getNextSibling()if __name__ == '__main__':    test()

    Here is another example. This one also prints out the text values of the name elements:

    """To run this example, set your CLASSPATH with something like the following:    export CLASSPATH=\    ${path-to-jython2.2a}/jython.jar:\    ${path-to-xerces}/xerces-2_8_0/xercesImpl.jar:\    ${path-to-xerces}/xerces-2_8_0/xml-apis.jar"""import sysfrom org.apache.xerces.parsers import DOMParser as dpdef test(infilename):    """Parse XML document and show attributes and names.    """    parser = dp()    parser.parse(infilename)    doc = parser.getDocument()    node = doc.getFirstChild()    print 'Attributes:'    show_attrs(node)    print 'Names:'    show_names(node)def show_attrs(node):    """Show the attributes and their values.    """    node = node.getFirstChild()    while node:        if node.getNodeType() == node.ELEMENT_NODE:            print ' %s:' % (node.getTagName(), )            attrs = node.getAttributes()            count = attrs.getLength()            for idx in range(count):                attr = attrs.item(idx)                print ' %s: %s' % (                    attr.getNodeName(), attr.getNodeValue(), )        node = node.getNextSibling()def show_names(node):    """Show the value of the name element for each person element.    """    node = node.getFirstChild()    while node:        if (node.getNodeType() == node.ELEMENT_NODE and            node.getTagName() == 'person'):                show_person_name(node)        node = node.getNextSibling()def show_person_name(node):    node = node.getFirstChild()    while node:        if (node.getNodeType() == node.ELEMENT_NODE and            node.getTagName() == 'name'):                show_text('name: ', node)        node = node.getNextSibling()def show_text(msg, node):    """Show a message and the value of a text node.    """    node = node.getFirstChild()    while node:        if node.getNodeType() == node.TEXT_NODE:            print ' %s %s' % (msg, node.getNodeValue(), )        node = node.getNextSibling()def usage():    print 'Usage: jython <infilename>'    sys.exit(-1)def main():    args = sys.argv[1:]    if len(args) != 1:        usage()    test(args[0])if __name__ == '__main__':    main()


    • Except for the parser set-up (in function test), this example is almost the same as the JAXP example. For the most part, it usesthe same API.


    • Xerces Java Parser
    • Introduction to XML and XML With Java
    7.2.3   dom4j   Installation and setup

    • Download dom4j from: dom4j: the flexible XML framework for Java —
    • Add the dom4j jar file to your CLASSPATH.
    • In order to get some features to work, I also had to install the jaxen XPath engine. Add that to your CLASSPATH, too.See: jaxen: universal Java XPath engine —   Examples etc

    There are examples at:

    • dom4j – Quick Start Guide —
    • dom4j cookbook —

    Example 1a — This example parses an XML document (file), then walks the dom4j DOM element tree and prints out information on each node:

    import sysfrom import SAXReaderdef show_indent(level):    return ' ' * leveldef show_node(node, level):    """Display one node in the DOM tree.    """    if node.getNodeType() == node.ELEMENT_NODE:        name = node.getName()        print '%sElement node: %s' % (show_indent(level), name, )        attrs = node.attributes()        for attr in attrs:            aName = attr.getQualifiedName()            aValue = attr.getValue()            print ' %sAttr -- %s: %s' % (show_indent(level), aName, aValue,)        if node.text:            print ' %sText: "%s"' % (show_indent(level), node.text,)def show_tree(node, level):    show_node(node, level)    level1 = level + 1    if node.getNodeType() == node.ELEMENT_NODE:        children = node.elements()        for child in children:            show_tree(child, level1)def test(infilename):    print 'Version: %s' % (sys.version, )    reader = SAXReader()    doc =    root = doc.getRootElement()    show_tree(root, 0)def main():    args = sys.argv[1:]    if len(args) != 1:        print 'usage: in_xml_file'        sys.exit(1)    test(args[0])if __name__ == '__main__':    #import pdb; pdb.set_trace()    main()


    • We use node.elements() to get all children that are elements, but not, for example, text nodes.

    Example 1b — This example also parses an XML document (file), thenwalks the dom4j DOM element tree and prints out information on each node. However, at each node it iterates over all the content nodes, including text nodes:

    import sysfrom import SAXReaderdef show_indent(level):    return ' ' * leveldef show_node(node, level):    """Display one node in the DOM tree.    """    if node.getNodeType() == node.ELEMENT_NODE:        name = node.getName()        print '%sElement node: %s' % (show_indent(level), name, )        attrs = node.attributes()        for attr in attrs:            aName = attr.getQualifiedName()            aValue = attr.getValue()            print ' %sAttr -- %s: %s' % (show_indent(level), aName, aValue,)    elif node.getNodeType() == node.TEXT_NODE:        print '%sText node: "%s"' % (show_indent(level), node.text, )def show_tree(node, level):    show_node(node, level)    level1 = level + 1    if node.getNodeType() == node.ELEMENT_NODE:        children = node.content()        for child in children:            show_tree(child, level1)def test(infilename):    print 'Version: %s' % (sys.version, )    reader = SAXReader()    doc =    root = doc.getRootElement()    show_tree(root, 0)def main():    args = sys.argv[1:]    if len(args) != 1:        print 'usage: in_xml_file'        sys.exit(1)    test(args[0])if __name__ == '__main__':    #import pdb; pdb.set_trace()    main()


    • We use node.content() to get all child nodes, including text nodes.

    • Use tests such as the following to determine whether a node is an element node or a text node:

      if node.getNodeType() == node.ELEMENT_NODE:    o    o    oelif node.getNodeType() == node.TEXT_NODE:    o    o    o

    Example 2 — This example creates an dom4j documentobject and adds element objects to it:

    import sysimport org.dom4j.DocumentHelperimport import XMLWriterfrom import OutputFormatdef test():    # 1.    # Create a new document and add a few elements to it.    doc = org.dom4j.DocumentHelper.createDocument()    root = doc.addElement('specs')    e1 = root.addElement('class1')    e1.addAttribute('name', 'dave')    e1.addAttribute('category', 'medium')    e1.addText('some simple content')    e1 = root.addElement('class2')    e1.addAttribute('name', 'mona')    e1.addAttribute('category', 'good')    e1.addText('more content')    # 2.    # Print a text representation of the DOM tree.    text = doc.asXML()    print text    print '\n', '-' * 40, '\n'    # 3.    # Print a formatted (pretty-print) representation.    format = OutputFormat.createPrettyPrint()    writer = XMLWriter(sys.stdout, format)    writer.write(doc)    print '\n', '-' * 40, '\n'    print 'root:', root, '\n'    # 4.    # Iterate over the children of the root.    # Print child and parent names, etc.    itr = root.elementIterator()    for idx, child in enumerate(itr):        print idx, child        parent = child.getParent()        print 'parent:', parent.getName()        print 'child:', child.getName()        print 'text: "%s"' % child.getText()        printtest()

    Notes — What this example does:

  • Creates a new document and adds a few elements to it.
  • Produces and prints a text representation of the DOM tree.
  • Prints a formatted (pretty-print) representation.
  • Iterates over the children of the root. Prints child and parent names, etc.
  • Resources:

    7.2.4   XMLBeans

    XMLBeans provides the ability to generate Java bindings for an XML document type from an XML Schema. Roughly speaking, XMLBeans generates a Java class for each element type defined in an XML Schema.

    Whenused with Jython, those Java bindings become quite Jythonic.

    You can read about XMLBeans here:

    • Welcome to XMLBeans —
    • XMLBeans at Wikipedia —   An example

    This example was copied from XMLBeans at Wikipedia — and then adapted to Jython.

    The XML Schema:

    <?xml version="1.0" encoding="UTF-8"?><xs:schema targetNamespace=""           xmlns:tns=""           xmlns:xs=""           elementFormDefault="qualified"           attributeFormDefault="unqualified"           version="1.0">  <xs:element name="Country" type="tns:Country"/>  <xs:complexType name="Country">    <xs:sequence>      <xs:element name="Name" type="xs:string"/>      <xs:element name="Population" type="xs:int"/>      <xs:element name="Iso" type="tns:Iso"/>    </xs:sequence>  </xs:complexType>  <xs:complexType name="Iso">    <xs:annotation><xs:documentation>ISO 3166</xs:documentation></xs:annotation>    <xs:sequence>      <xs:element name="Alpha2" type="tns:IsoAlpha2"/>      <xs:element name="Alpha3" type="tns:IsoAlpha3"/>      <xs:element name="CountryCode" type="tns:IsoCountryCode"/>    </xs:sequence>  </xs:complexType>  <xs:simpleType name="IsoCountryCode">    <xs:restriction base="xs:int">      <xs:totalDigits value="3"/>    </xs:restriction>  </xs:simpleType>  <xs:simpleType name="IsoAlpha2">    <xs:restriction base="xs:string">      <xs:pattern value="[A-Z]{2}"/>      <xs:whiteSpace value="collapse"/>    </xs:restriction>  </xs:simpleType>  <xs:simpleType name="IsoAlpha3">    <xs:restriction base="xs:string">      <xs:pattern value="[A-Z]{3}"/>      <xs:whiteSpace value="collapse"/>    </xs:restriction>  </xs:simpleType></xs:schema>

    Supposing that you name the above schema country.xsd, you can compile this with XMLBeans using something like the following:

    $ scomp -out country.jar country.xsd

    Here is abit of Java code, copied from Wikipedia, that uses the generated Java classes:

    import;import;public class CountrySample{  public static void main(String[] args) {    Country country = Country. Factory.newInstance();    country.setName("Denmark");    country.setPopulation(5450661); // from wikipedia :-)    // print out country XMLBean as XML    System.out.println(country.xmlText());    // check if document is valid - will print "Document is invalid"    // because required Iso child element in not in the object    System.out.println ("Document is " + (country.validate() ? "valid" : "invalid"));    // add child with complex type Iso to make the document valid    Iso iso = country.addNewIso();    iso.setAlpha2("DK");    iso.setAlpha3("DNK");    iso.setCountryCode(208);    // print out country XMLBean as XML    System.out.println(country.xmlText());    // check if document is valid - will print "Document is valid"    System.out.println ("Document is " + (country.validate() ? "valid" : "invalid"));  }}

    After translation to Jython, here is the equivalent code. Note that it uses the same generated Java classes as the above Java code:

    from import Countryfrom import Isofrom org.apache.xmlbeans import XmlOptionsclass CountrySample(object):    def main(self, args):        country = Country.Factory.newInstance()        country.setName("Denmark")        country.setPopulation(5450661); # from wikipedia :-)        # Print out country XMLBean as XML.        print country.xmlText()        # Print out country XMLBean as XML with indentation.        opts = XmlOptions()        opts.setSavePrettyPrint()        opts.setSavePrettyPrintIndent(4)        print country.xmlText(opts)        # Check if document is valid - will print "Document is invalid"        # because required Iso child element in not in the object.        if country.validate():            condition = "valid"        else:            condition = "invalid"        print "Document is", condition        # Add child with complex type Iso to make the document valid.        iso = country.addNewIso();        iso.setAlpha2("DK")        iso.setAlpha3("DNK")        iso.setCountryCode(208)        # Print out country XMLBean as XML.        print country.xmlText(opts)        # Check if document is valid - will print "Document is valid".        if country.validate():            condition = "valid"        else:            condition = "invalid"        print "Document is", conditiondef test():    country_sample = CountrySample()    country_sample.main([])test()

    Add the generated jar file to your CLASSPATH. In Linux, I can do that with the following:

    $ export CLASSPATH=$CLASSPATH:./country.jar

    Now run it:

    $ jython

    And, that prints out:

    <xml-fragment><v1:Name xmlns:v1="">Denmark</v1:Name><v1:Population xmlns:v1="">5450661</v1:Population></xml-fragment><xml-fragment>    <v1:Name xmlns:v1="">Denmark</v1:Name>    <v1:Population xmlns:v1="">5450661</v1:Population></xml-fragment>Document is invalid<xml-fragment>    <v1:Name xmlns:v1="">Denmark</v1:Name>    <v1:Population xmlns:v1="">5450661</v1:Population>    <v1:Iso xmlns:v1="">        <v1:Alpha2>DK</v1:Alpha2>        <v1:Alpha3>DNK</v1:Alpha3>        <v1:CountryCode>208</v1:CountryCode>    </v1:Iso></xml-fragment>Document is valid

    7.3   Database access

    7.3.1   JDBC

    JDBC is Java classes. It is, therefore, usable from Jython.

    You will need JDBC driver/adapters for your database.

    But, JDBC is not very Pythonic.

    7.3.2   zxJDBC

    zxJDBC is Pythonic. zxJDBC implements the Python DB API on top of JDBC. For more on the Python DB API, see SIG on Tabular Databases in Python and Python Database API Specification v2.0.

    If zxJDBC is not already in your installed version ofJython, then you can:

  • Downloading the source from
  • Creating a directory (e.g. zxJDBC), then un-rolling it.
  • Add zxJDBC/lib/zxJDBC.jar to your CLASSPATH
  • You can get documentation on zxJDBC by:

  • Downloading the source from
  • Creating a directory (e.g. zxJDBC), then un-rolling it.
  • Pointing your browser at zxJDBC/doc/index.html.
  • Example — The following example opens a connection to a PostgreSQL database, then prints out the rows in a table in that database. In order to make this example work, I put the following jar files on my CLASSPATH:

    • zxJDBC.jar– Not needed for Jython 2.2, and possibly not needed for the version of Jython 2.1 on your machine. JDBC support has been folded into Jython 2.1 and Jython 2.2a.
    • postgresql-8.1-407.jdbc3.jar — You will need a suitable driver for your database and version.

    Here is the example implementation:

    """For this test, add the JDBC driver to your CLASSPATH. For example,in my case I added:    postgresql-8.2-506.jdbc4.jar"""from com.ziclix.python.sql import zxJDBCdef test():    d, u, p, v = (        "jdbc:postgresql://thrush:5432/test", # ... host, port, database        "postgres", # user name        "mypassword", # pass word        "org.postgresql.Driver", # driver        )    db = zxJDBC.connect(d, u, p, v, CHARSET='iso_1')    cur = db.cursor()    cur.execute('select * from plant_db')    rows = cur.fetchall()    s1 = '%s %s %s' % (        'Name'.ljust(12),        'Description'.ljust(24),        'Rating'.ljust(10),        )    print s1    s1 = '%s %s %s' % (        '===='.ljust(12),        '==========='.ljust(24),        '======'.ljust(10),        )    print s1    for row in rows:        rating = str(row[2])        print '%s %s %s' % (            row[0].ljust(12), row[1].ljust(24), rating.ljust(10), )    cur.close()    db.close()if __name__ == '__main__':    test()

    Which, when connected to my trivial, little database, prints out the following:

    Name Description Rating==== =========== ======tomato red and tasty 8peach sweet and succulent 8tangerine sweet but tart 7


    • More information on zxJDBC:
    • The JDBC driver for PostgreSQL:
    • The JDBC driver for MySQL:
    • Python Tabular Databases SIG: Status —
    • The Python Database Topic Guide —

    9   Referencesand Sources

    Introductory articles:

    • An Introduction to Jython: An introductory article on Jython
    • alt.lang.jre: Get to know Jython: An introduction to Jython that includes a summary of Jython features.
    • Use Jython toExercise Java APIs Without Compiling: Another introduction with an emphasis on the use of Java classes.
    • Charming Jython: Yet another introductory article.
    • Scripting Languages For Java: A comparison of scripting languages for Java.

    Thanks to David Goodger for the following list or references.His “Code Like a Pythonista: Idiomatic Python” ( is worth a careful reading:

    • “Python Objects”, Fredrik Lundh,
    • “How to think like a Pythonista”, Mark Hammond,
    • “Python main() functions”, Guido van Rossum,
    • “Python Idioms and Efficiency”,
    • “Pythontrack: python idioms”,
    • “Be Pythonic”, Shalabh Chaturvedi,
    • “Python Is Not Java”, Phillip J. Eby,
    • “What is Pythonic?”, Martijn Faassen, http://faassen.n–
    • “Sorting Mini-HOWTO”, Andrew Dalke,
    • “PythonIdioms”,
    • “Python FAQs”,
    How do you use Jython in Python? : 2.3 Running Jython
    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.
    Read Detail Answer On How do you use Jython in Python?

    Since Jython is an implementation of Python for the JVM, most of the standard Python documentation applies. Look in the following places for general information:

    • The Python Tutorial (start here)
    • ThePython Library Reference. Although many of these modules are not yet implemented (those coded in C for CPython must be re-implemented in Java for Jython), those that are implemented follow the library reference as closely as possible.
    • The Python Language Reference (for language lawyers).

    Other Useful Links

    • Jython and CPython are two different implementations of the same language. There are naturally some differences between the two implementations, sometimes reflecting undefined aspects of the Python language, sometimes reflecting quirks of the independent implementations.
    • TheJython FAQ may already contain the answer to your question.
    • If it doesn’t, then check Jython-users mailing list archives.
    • If you are still stuck you can post a question to the Jython-users mailing list

    Invoking the Jython Interpreter

    Jython is invoked using the “jython” script, a short script that invokes your local JVM, sets the Java property install.path to an appropriate value, and then runs the Java classfile org.python.util.jython.

    jython [options] [-jar jar | -c cmd | file | -] [args]

    options-i: Inspect interactively after running script; force prompts even if stdin is not a terminal. -S: Do not imply import site on initialization -Dprop=[value]: Set the jython property prop to value.-jar jarthe program to run is read from the file in the specified jar file

    -c cmd program to run is passed in as the cmd string. This option terminates the options list file run file as the program script file
    • program is read from standard-in (default; interactive mode is used if on a tty). This flag allows you to pipe a file into Jython and have it be treated correctly. For example:

      filter file | jython –

    argsarguments passed to the program in sys.argv[1:]

    –help print a usage message and exit
    –version print Jython version number and exit

    Making Jython Scripts Executable

    To make a jython “.py” file executable on a Unix system:

    • Make sure that jython is on your standard PATH.
    • Make the “.py” file executable. Typically, this is done with the command chmod +x
    • Add the following line tothe top of the file:

    #! /usr/bin/env jython


    “#! <…>/jython” will generally not work to make your script executable. This is because “jython” is itself a script, and #! requires that the file to execute is a binary executable on most Unix variants. Using “/usr/bin/env” will get around this problem – and make your scripts more portable in the bargain.

    The Jython Registry

    Because there is no good platform-independent equivalent of the Windows Registry or Unix environment variables, Java has its own environment variable namespace. Jython aquires its namespace from the following sources (later sources override defaults found in earlier places):

    • The Java system properties, typicallypassed in on the command line as options to the java interpreter.
    • The Jython “registry” file, containing prop=value pairs. See below for the algorithm Jython uses to find the registry file.
    • The user’s personal registry file, containing similarly formated prop/value pairs. The user’s registry file can be found at “user.home”+”/.jython”
    • Jython properties specified on the command line as options to the jython class. See the -D option to the interpreter.

    Registry Properties

    The following properties are recognized by Jython. There may be others that aren’t documented here; consult the comments in registry file for details.

    python.pathEquivalent to CPython’s PYTHONPATH environment variablepython.cachedirThe directory to use for caches – currently justpackage information. This directory must be writable by the user. If the directory is an absolute path, it is used as given, otherwise it is interpreted as relative to sys.prefix.python.verboseSets the verbosity level for varying degrees of informative messages. Valid values in order of increasing verbosity are “error”, “warning”, “message”, “comment”, “debug”, Jython can only provide access to public members ofclasses. However if this property is set to false and you are using Java 1.2 then Jython can access non-public fields, methods, and constructors.python.jythonc.compilerThe Java compiler to use with the jythonc tool, which now generates Java source code. This should be the absolute path to a Java compiler, or the name of a compiler on your standard PATH.python.jythonc.classpathExtensions to the standard java.class.path property for use with jythonc. This isuseful if you use Jikes as your compiler.python.jythonc.compileroptsOptions to pass to the Java compiler when using jythonc.python.consoleThe name of a console class. An alternative console class that supports GNU readline can be installed with this property. Jython already include such a console class and it can be enabled by setting this property to org.python.util.ReadlineConsolepython.console.readlinelibAllow a choice of backingimplementation for GNU readline support. Can be either GnuReadline or Editline. This property is only used when python.console is set to org.python.util.ReadlineConsole.

    Finding the Registry File

    To find the Jython registry file and set the Python values for sys.prefix, you must first locate a rootdirectory.

    • If a “python.home” exists, it is used as the root directory by default.
    • If “python.home” does not exist, “install.root” is used.
    • If neither of these exist, then Jython searches for the file “jython.jar” on the Java classpath, as defined in the system property java.class.path. (The actual file system isn’t searched, only the paths defined on the classpath and one of them must literally include “jython.jar”).

    Once the root directory is found,sys.prefix and sys.exec_prefix are set to this, and sys.path has rootdir/Lib appended to it. The registry file used is then rootdir/registry.

    Interaction with Java Packages

    Most Jython applications will want to use the vast array of Java packages available. The following documentation helpsyou work with Java packages.

    • Working with JavaBean properties, making all Java classes easier to use from Python.
    • Special care is necessary to build and use Java arrays from Python.
    • This document describes how to subclass Java classes in Python.
    • The jythonc utility compiles Python source code to real Java classes, and is used for building applets, servlets, beans,etc.
    • Unloading of java classes and internalTablesImpl option.
    • Reloading java classes.

    Accessing Java from Jython

    One of the goals of Jython is to make it as simple as possible to use existing Java libraries from Python. Example

    The following example of an interactive session withJython shows how a user could create an instance of the Java random number class (found in java.util.Random) and then interact with that instance.

    C:\jython>jythonJython 2.0 on java1.2.1Type "copyright", "credits" or "license" for more information.>>> from java.util import Random>>> r = Random()>>> r.nextInt()-790940041>>> for i in range(5):...     print r.nextDouble()...0.233476815061238520.85265955921895460.36478338399881370.33848652605672780.5514469740469587>>>

    More Details

    Hopefully, this example should make it clear that there are very few differences between using Java packages and using Python packages when working under Jython. Thereare a few things to keep in mind.


    Jython 2.0 on java1.2.1Type "copyright", "credits" or "license" for more information.>>> from java.util import *>>> Random<jclass java.util.Random at 31702169>>>> Hashtable<jclass java.util.Hashtable at 7538094>>>>

    Creating Class Instances

    You can create an instance of a Java class exactly the way you would create aninstance of a Python class. You must “call” the class with a set of arguments that is appropriate for one of the Java class’s constructors. See the section below for more details on what constitutes appropriate arguments.

    Calling Java Methods and Functions

    Java classes have both static andinstance methods this makes them behave much like a cross between a Python module and class. As a user, you should rarely need to be concerned with this difference.

    Java methods and functions are called just exactly like their Python counterparts. There is some automatic type coercion that goes on both for the types being passed in and for the value returned by the method. The following table shows how Python objects are coerced to Java objects when passed as arguments in a function call.The Java Types show the expected Java type for the argument, and the Allowed Python Types shows what Python objects can be converted to the given Java type. Notice the special behavior of String’s when a java.lang.Object is expected. This behavior might change if it is shown to cause problems.

    Java TypesAllowed Python Types

    char String (must have length 1)
    boolean Integer (true = nonzero)
    byte, short, int, long Integer
    float, double Float
    java.lang.String, byte[], char[] String
    java.lang.Class Class or JavaClass (only if class subclasses from exactly one Java class; mutiple inheritance from more than one Java class is now illegal)
    Foo[] Array (must contain objects of class or subclass of Foo)
    java.lang.Object String->java.lang.String, all others unchanged
    org.python.core.PyObject All unchanged
    Foo Instance->Foo (if Instance is subclass of Foo); JavaInstance -> Foo (if JavaInstance is instance of Foo or subclass)

    Returned values from a Java method are also possibly coerced back to an object that is more readily usable in Python. The following table shows those coercions.

    Java TypeReturned Python Type

    char String (of length 1)
    boolean Integer (true = 1, false = 0)
    byte, short, int, long Integer
    float, double Float
    java.lang.String String
    java.lang.Class JavaClass which represents given Java class
    Foo[] Array (containing objects of class or subclass of Foo)
    org.python.core.PyObject (or subclass) Unchanged
    Foo JavaInstance which represents the Java Class Foo

    Overloaded Java Method Signatures

    Java methods are allowed to be overloaded for different signatures (types and number of arguments). When different versions of the method differ in the number of arguments that they expect, the appropriate method can be easily determinedfrom the number of arguments passed to the method.

    When the difference is instead in the types of the arguments, more work is required. The possible signatures are sorted in a consistent order that should ensure the appropriate method is chosen first. TBD: document this order!

    If you need to call a Java method with a particular signature and this is not happening in the easy way, you can use the following workaround:

    Assume that foo has two methods, “void foo(int x); voidfoo(byte x);”. To call the second method you could write the following:

    from java.lang import Bytefoo(Byte(10))

    I’m not convinced that any better solution to this problem is possible.


    Look into IronPython’s solution to this for ideas.

    Naming Conflicts with Python Keywords

    Because Javahas a different set of keywords than Python, there are many Java classes that have method and function names that conflict with Python’s keyword set. Where the intent can be unambiguously determined, no identifier mangling is necessary, such as when keywords are used as attributes on objects. Thus you can naturally write:




    In the rare case where the conflictcan’t be resolved due to Python’s grammar, you should modify the reserved word by appended an underscore to the end of it, e.g. print_

    JavaBean Properties


    Jython uses JavaBean properties to make it easier to interact with most Java classes. These properties can be used as normal object attributes, and can also be specified to the class constructor as keyword arguments (this idea is stolen from TkInter where it seems to work extremely well).

    These properties are generated automatically by the JavaBean Introspector, which recognizes properties from BeanInfo that has been explicitly specified or from popular design patterns.

    As a first example, consider the case where you wish to create a button that is disabled.

    The first example shows how you would do this in the typical Java fashion:

    b = awt.Button()b.setEnabled(0)

    The second example shows how enabled can be set as a property:

    b = awt.Button()b.enabled = 0

    The final example sets this property at instantiation time using a keyword argument:

    b = awt.Button(enabled=0)


    If the value of a property is specified as a tuple, then the property will be created by applying the constructor for the type of the property to the tuple. This is particularly handy for specifying sizes:

    frame = awt.Frame(size=(500,100))

    It can also be handy for specifying color as an RGB triple:

    frame.background = 255,255,0

    will set the background color of the frame to yellow.

    Event Properties

    In standard Java, the event handlers for a widget are specified by passing in an instance of a class that implements the appropriate interface. This is the only reasonable approach to take in a language that doesn’t have first-class functions. In Jython, for every event listener supported by a class, there will be aproperty added to the class for each method supplied by the event listener class. These properties can be set to give a function to be called when the appropriate event occurs.

    The standard Java style for setting an event listener is shown below:

    class action(awt.event.ActionListener):    def actionPerformed(self,event):        java.lang.System.exit(0)button = awt.Button("Close Me!")button.addActionListener(action())

    This can be written in a more Pythonesque (and compact) style by using event properties as follows:

    def exit(event):  java.lang.System.exit(0)button = awt.Button("Close Me!", actionPerformed=exit)

    Methods, Properties and Event Properties

    Jython have only one namespace for these three class attributes. Java can be seen as having a unique namespace for each of the three types. As a consequense, there can be conflicts between methods, properties and event properties. These conflicts are resolved sothat:

    properties < event-properties < fields < methods

    This means that a method will override a field with the same name. Some carefull handling of properties and static fields allow for the existence of, and access to, both an instance property and a static field with the same name.

    Java Arrays

    Java Arrays in Jython – JArray Many Java methods require Java array objects as arguments. The way that these arguments are used means that they must correspond to fixed-length, mutable sequences, sometimes of primitive data types. The PyArray class is added to support these Java arrays and instances of this class will be automatically returned from any Java method call that produces an array. In addition, the “jarray” module is provided to allow users of Jython to create these arraysthemselves, primarily for the purpose of passing them to a Java method.

    The jarray module exports two functions:

    array(sequence, type)zeros(length, type)

    array will generate a fresh array that is the same size as the input sequence and fill it with the values in order. A new array of the specified length will be created and filled with zeros (or nulls, as appropriate).

    type can either be a single character typecode (using the same mappings as Python’s array module) or it can be an instance of a JavaClass object.The valid typecodes are shown in the following table:

    Character TypecodeCorresponding Java Type

    z boolean
    c char
    b byte
    h short
    i int
    l long
    f float
    d double

    A quick example:

    from jarray import arraya = array([ 1 ], 'i')print afrom import URLu = URL('')b = array([], URL)print b

    Subclassing Java Classes in Jython

    A Short Example

    The example below should bothdemonstrate how this subclassing is performed and why it is useful. At first glance, the code looks exactly like subclassing any other Python class. The key difference in this example is that awt.event.ActionListener is a Java class, not a Python one. In the 4th line from the end, “b.addListener(SpamListener())”, a Java method is being called that requires an instance of the Java class ActionListener. By providing a Python subclass of this Java class, everybody is happy.

    from java import awtclass SpamListener(awt.event.ActionListener):    def actionPerformed(self,event):        if event.getActionCommand() == "Spam":            print 'Spam and eggs!'f = awt.Frame("Subclassing Example")b = awt.Button("Spam")b.addActionListener(SpamListener())f.add(b, "Center")f.pack()f.setVisible(1)

    Note: Thisexample can be accomplished much more elegantly by using JavaBeans properties (and event properties).

    Calling Methods in Your Superclass

    In Python, if I want to call the foo method in my superclass, I use the form:

    This works with the majority of methods, but protected methodscannot be called from subclasses in this way. Instead you have to use the “self.super__foo()” call style.


    The following example shows how the class can be effectively subclassed. What makes this class difficult is that the read method is overloaded for three different method signatures:

  • abstract intread()
  • int read(byte[])
  • int read(byte[], int, int)
  • The first one of these methods must be overridden in a subclass. The other two versions can be ignored. Unfortunately, Python has no notion of method overloading based on type signatures (this might be related to the fact that Python doesn’t have type signatures 😉 In order to implement a subclass of that overrides the “read” method, a Python method must be implemented that handles all threepossible cases. The example below shows the easiest way to acheive this:

    from import InputStreamclass InfiniteOnes(InputStream):    def read(self, *args):        if len(args) > 0:        # int read(byte[])        # int read(byte[], int, int)            return apply(, (self,)+args)        return 1io = InfiniteOnes()for i in range(10):    print,print

    Example Continued

    To continue the example above, this new instance of can be passed to any Java method that expects an InputStream as shown below:

    from import DataInputStreamdp = DataInputStream(io)dp.skipBytes(1000)print dp.readByte()print dp.readShort()print dp.readInt()

    Invoking Your Superclass’s Constructor

    You can explictly invoke your superclass’s constructor using the standard Python syntax of explictly calling the “__init__” method on the superclass and passing in “self” as the first argument. If you wish to call your superclass’s constructor, you must do so withinyour own “__init__” method. When your “__init__” method finishes, if your Java superclasses have not yet been explicitly initialized, their empty constructors will be called at this point.

    READ More:  Fairy Fencer F: Additional Fairy Pack On Steam Free Download Full Version

    It’s important to realize that your superclass is not initialized until you either explictly call it’s “__init__” method, or your own “__init__” method terminates. You must do one of these two things before accessing any methods in your superclass.


    from java.util import Randomclass rand(Random):    def __init__(self, multiplier=1.0, seed=None):        self.multiplier = multiplier        if seed is None:            Random.__init__(self)        else:            Random.__init__(self, seed)    def nextDouble(self):        return Random.nextDouble(self) * self.multiplierr = rand(100, 23)for i in range(10):    print r.nextDouble()

    This example shows how the superclass’s constructor can be effectively called in order to explictly choose a non-empty version.

    Embedding Jython

    There are two ways to incorporate Python into a Java application. As previously mentioned, you can convert a Python class into a real Java class and then use it in your Java code, or you can use the PythonInterpreter object.

    Information on the PythonInterpreter can be found in the JavaDoc documentation for org.python.util.PythonInterpreter.

    The following example demonstrates how to use the PythonInterpreter toexecute a simple Python program.

    The python program:

    import sysprint sysa = 42print ax = 2 + 2print "x:",x

    The java code required to execute the python program:

    import org.python.core.PyException;import org.python.core.PyInteger;import org.python.core.PyObject;import org.python.util.PythonInterpreter;public class SimpleEmbedded {    public static void main(String[] args) throws PyException {        PythonInterpreter interp = new PythonInterpreter();        interp.exec("import sys");        interp.exec("print sys");        interp.set("a", new PyInteger(42));        interp.exec("print a");        interp.exec("x = 2+2");        PyObject x = interp.get("x");        System.out.println("x: " + x);    }}

    Using JSR 223

    JSR 223, Scripting for the Java language, added the javax script pacakge to Java 6 It allows multiple scripting languages to be used through the same API as long as the language provides ascript engine The scripting project contains such an engine for Jython It can be used to embed Jython in your application alongside many other languages that have script engines such as JRuby or Groovy

    The usage of PythonInterpreter above translates to the following using JSR 223:

    import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.script.ScriptException;public class JSR223 {    public static void main(String[] args) throws ScriptException {        ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");        engine.eval("import sys");        engine.eval("print sys");        engine.put("a", 42);        engine.eval("print a");        engine.eval("x = 2 + 2");        Object x = engine.get("x");        System.out.println("x: " + x);    }}

    To use JSR 223 with Jython, download theengine and add it to your classpath along with Jython. Then use code like the above to create and use an engine. One difference between embedding with JSR 223 and using PythonInterpreter directly is that the scripting engine manages its own PySystemState per thread so it can always set the classloader to the thread’s context classloader. This means if you want to do anything Jython specific to PySystemState, like adding to sys.path or setting sys.stdin and sys.stdout, you should do it aftercreating the ScriptEngine.

    Java Reload (experimental) simple Support – JReload

    Introduction and usage, plus some notes on java classes unloading and internalTablesImpl option

    The “jreload” module is not the definitive word about java classes reloadingunder jython. It is still experimental and its interface may improve or change to become more pythonic.

    “jreload” cannot cover all the possible reload-flavors, and its goal is to offer a simple interface for the most common cases, e.g. quick trial-and-error experimenting.

    Java classes reloading in jython is not enabled by “jreload”, some of the modifications occurred to jython run-time have made it possible. Now jython can deal with java classes with the same name (without clashes)and run-time supports unloading of java classes by different ways, which is a must feature for some uses of reloading

    [The expert user can now play directly with class-loaders and reloading as he would from java.]

    The main idea of the “jreload” interface is that of a load-set. A load-set is a package-like object that can host a complete hierarchy of java packages, which can be reloaded as a whole.

    Why there is no support for reloading a single class? Java classes are loadedthrough class-loaders, actually there is no support in java to redefine an already loaded class through its class-loader. In order to reload a class one should create a new class-loader, but classes from different class-loaders cannot interoperate, so we need to reload all related classes through the new class-loader. Note: The normal python reload built-in does nothing for java classes and simply returns the old version.

    The “jreload” module exports the following functions:

    makeLoadSet(name, path)reload(loadSet)

    makeLoadSetcreates and returns a new load-set with the given name The created load-set will behave like a package and import statement related to it can be issued name should be a valid python identifier like any python module name and should not clash with any module that has been or will be imported Internally the created load-set will be added to sys modules, the same way it happens to modules on import You can issue the same makeLoadSet from many places, it is idempotent like modules imports are

    path should be a list of directory or jar paths. The created load-set will enable importing the classes present there. path should be disjoint from both sys.path and java classpath, otherwise one can get very confusing results.

    For example: if a load-set ‘X’ is created and its hierarchy contains java packages ‘p’ and ‘p.q’, then the following references can be used in import statements: ‘X’, ‘X.p’, ‘X.p.q’.

    reload(loadSet) reloads all the classes in the package hierarchy hosted byloadSet and returns loadSet.


    The current version of “jreload” (jreload.__version__==’0.3′) does not support removing or substituting jars on the fly.


    The following example should help make things clearer: (its files should be present in the jython Demo dir) # Demo/jreload/example.jar contains example.Version (source) andexample.PrintVer (source) # Demo/jreload/_xample contains a slightly modified version of example.Version (source)

    >>> import sys>>> import os>>> import jreload>>> def xp(name): return os.path.join(sys.prefix,'Demo/jreload/'+name)# builds a path under 'Demo/jreload'...>>> X=jreload.makeLoadSet('X',[xp('.'),xp('example.jar')])>>> from X import example>>> dir(example)['PrintVer', 'Version', '__name__']>>> X.example.Version<jclass example.Version at 6781345>>>> from X.example import * # works but in general import * from javapkgs is not for production code>>> v=Version(1)>>> PrintVer.print(v)version 1>>> os.rename(xp('_xample'),xp('example')) # _xample becomes example,hiding and "patching" jar contents>>> jreload.reload(X) # (re)loads example dir example.Version andjar example.PrintVer<java load-set X>>>> nv2=example.Version(2)>>> example.PrintVer.print(nv2)new version 2>>> PrintVer.print(nv2)Traceback (innermost last):  File "<console>", line 1, in ?TypeError: print(): 1st arg can't be coerced to example.Version>>> example.PrintVer.print(v)Traceback (innermost last):  File "<console>", line 1, in ?TypeError: print(): 1st arg can't be coerced to example.Version>>> os.rename(xp('example'),xp('_xample'))


    Differently from python packages reload, load-sets reload the complete hosted hierarchy.


    Class versions across reloads are not interoperable.

    Like for python classes and python reload, old versions are kept around, if there are still references to them. But what happens if they are no longer used?

    Java Classes Unloading

    One would expect that no longer referenced java classes would be unloaded, but the situation is not that simple.

    In order to give a python-class-like view on python side and for implementation reasons jython wraps java classes (in instances of org.python.core.PyJavaClass). Clearly the mapping from javaclasses to their wrapped version should be unique (e.g. to guarantee == and ‘is’ semantic). So jython keeps this mapping in an internal table. This is also good because building the wrappers is expensive.

    Note: Typically one should care about java classes unloading only for very dynamic applications, like IDEs or long-running apps, that would go out memory if old versions of reloaded classes would not be collected.

    Clearly the entries somehow block unloading. On the other hand javaclasses unloading is just a memory consumption optimization (and as such is it presented in Java Language Specification). Actual jvms clearly support this. JPython simply kept the entries in the table forever but Jython and “jreload” try to make unloading possible.

    Note: java never unloads system classes (java.* etc) nor classes from classpath. Further Jython cannot unload sys.path java classes. So the whole unload issue makes sense only with “jreload” or custom class-loaders. Java 2 andjython internalTablesImpl option

    Under java2 jython offers table implementations that exploit soft/weak references in order to discard entries (when this is OK) for unloading.

    A possible policy would be to keep an entry as long as the corresponding java class is still referenced outside the table (both by java or jython code). But this one cannot be implemented. [Tech.: One cannot add fields to final java class java.lang.Class!] So entries are kept as long as the wrapped version isstill in use. These implementations can be chosen trough python.options.internalTablesImpl registry option. Note: they only influence classes unloading, there is no need and reason to use them, unless one depends on class unloading to avoid memory leakage.

    internalTablesImpl = weak — Sets implementation using weak-refs. Table entries for not referenced (outside the table) wrapped versions are “discarded” at garbage collection points. If a class or some of its instances are continuouslypassed from java to jython side, but no long-living reference to it is kept from jython side, this can imply a performance penalty (rebuilding the wrapped version is expensive). On the other hand this is a good setting for testing if unloading actually happens or some references hunting around prevent it.

    [Note: With jdk 1.3 java -verbose:class can help tracking class unloads, and System.gc forces class unloading. With jdk 1.2 java -verbose:gc should give some information on classunloading, but unloading of classes happen at unpredictable points and System.gc does not trigger it. Also weak-refs allow testing for unloading and gc.]

    internalTablesImpl = soft –Sets implementation using soft-refs. Table entries for not referenced (outside the table) wrapped versions are “discarded” on memory shortage, given soft-reference definition. Soft-references behavior is not specified in full details, so the actual behavior will depend on the concrete jvm. But if actual (jvm)implementations are not too bad, this should be a good setting for production code, which relies on unloading to avoid out of memory failures.

    Java 1.1

    To be honest the unloading support that jython can offer under java 1.1 (given the absence of weak/soft-refs) is error-prone and anything serious would require “too much” caution, but thisshould not be a real issue. Support is offered only for “jreload” needs, in these forms:

    # Before reload(X) one can issue X.unload(). X.unload() discards all the entries for the old versions of the classes in X. This is safe only if all python subclasses and all instances of them have been destroyed. # One can “extract” the information needed in order to discard the entries for the versions actually present in X at a later point (after a whole series of reloads):

    u_t1=X.unload # extract unload info for time t1 versions … reloads … u_t1() # discard entries for time t1 versions

    u_t1() is safe only if at that point all subclasses/instances of the involved versions have been destroyed.


    these idioms work also with the standard internal tables implementation under java2, and for compatibility even with the weak/soft implementations.

    JReload Example Source Files

    Jar example.Version

    package example;public class Version { private int ver; public Version(int ver) {  this.ver = ver; } public String toString() {   return "version "+ver; }}


    package example;public class PrintVer { static public void print(Version ver) {  System.out.println(ver); }}

    New example.Version

    package example;public class Version { private int ver; public Version(int ver) {  this.ver = ver; } public String toString() {   return "new version "+ver; }}

    Databaseconnectivity in Jython

    The zxJDBC package provides a nearly 100% Python DB API 2.0 compliant interface for database connectivity in Jython. It is implemented entirely in Java and makes use of the JDBC API. This means any database capable of being accessed through JDBC, either directly or using the JDBC-ODBC bridge, can be manipulated using zxJDBC. Getting a Connection

    First, make sure a valid JDBC driver isin your classpath. Then start Jython and import the zxJDBC connection factory. Using a Driver

    The most common way to establish a connection is through a Driver. Simply supply the database, username, password and JDBC driver classname to the connect method. If your driver requires special arguments, pass them into the connect method as standard Python keyword arguments. You will be returned a connection object.

    Jython 2.1b1 on java1.4.0-beta3 (JIT: null)Type "copyright", "credits" or "license" for more information.>>> from com.ziclix.python.sql import zxJDBC>>> d, u, p, v = "jdbc:mysql://localhost/test", None, None,"">>> db = zxJDBC.connect(d, u, p, v) optionally>>> db = zxJDBC.connect(d, u, p, v, CHARSET='iso_1')>>>

    Using a DataSource (or ConnectionPooledDataSource)

    The only required argument is the fully-qualified classname of the DataSource, all keywords will use JavaBeans reflection to set properties on the DataSource.

    Jython 2.1b1 on java1.4.0-beta3 (JIT: null)Type "copyright", "credits" or "license" for more information.>>> from com.ziclix.python.sql import zxJDBC>>> params = {}>>> params['serverName'] = 'localhost'>>> params['databaseName'] = 'ziclix'>>> params['user'] = None>>> params['password'] = None>>> params['port'] = 3306>>> db = apply(zxJDBC.connectx, ("",),params)>>>

    Using a JNDI lookup

    It is possible for zxJDBC to use a Connection found through a JNDI lookup. This is particularly useful in an application server (such as when using PyServlet). The bound object can be either a String, Connection, DataSource or ConnectionPooledDataSource. The lookup will figure out the instance type and access theConnection accordingly,

    The only required argument is the JNDI lookup name. All keyword arguments will be converted to their proper Context field value if the keyword matches one of the constants. If a field name does not exist for the keyword, it will passed as declared. The resulting environment will be used to build the InitialContext.

    This example uses the simple Sun FileSystem JNDI reference implementation. Please consult the JNDI implementation you intend to use for theInitialContextFactory classname as well as the connection URL.

    Jython 2.1b1 on java1.4.0-beta3 (JIT: null)Type "copyright", "credits" or "license" for more information.>>> from com.ziclix.python.sql import zxJDBC>>> jndiName = "/temp/jdbc/mysqldb">>> factory = "com.sun.jndi.fscontext.RefFSContextFactory">>> db = zxJDBC.lookup(jndiName, INITIAL_CONTEXT_FACTORY=factory)>>>

    Getting a Cursor

    In order execute any operation, a cursor is required from the connection. There are two different kinds of cursors: static and dynamic.

    The primary difference between the two is the way they manage the underlying ResultSet. In thestatic version, the entire ResultSet is iterated immediately, the data converted and stored with the cursor and the ResultSet closed. This allows the cursor to know the rowcount (not available otherwise within JDBC) and set the .rowcount attribute properly. The major disadvantage to this approach is the space/time constraints might be extraordinary.

    The solution to the problem are dynamic cursors which keep a handle to the open ResultSet and iterate as required. This drastically decreasesmemory consumption and increases perceived response time because no work is done until asked. The drawback is the .rowcount attribute can never be accurately set.

    To execute a query simply provide the SQL expression and call execute. The cursor now has a description attribute detailing the column information. To navigate the result set, call one of the fetch methods and a list of tuples will be returned.

    >>> c = db.cursor()   # this gets a static cursor or>>> c = db.cursor(1)  # this gets a dynamic cursor>>> c.execute("select count(*) c from player")>>> c.description[('c', 3, 17, None, 15, 0, 1)]>>> for a in c.fetchall():...  print a...(13569,)>>>

    When finished, close the connections.

    >>> c.close()>>> db.close()>>>

    Give the name and any additional parameters to callproc when calling a stored procedure or function. Stored procedures must be supported by the database engine. Oracle, SQLServer, and Informix have all been used to test the examples that follow. See the Python DP API specification for details on how the OUT and INOUT parameters operate.


    The name of the stored procedure can either be a string or tuple. This is NOT portable to other DB API implementations.

    SQL Server

    >>> c = db.cursor() # open the database as in the examples above>>> c.execute("use northwind")>>> c.callproc(("northwind", "dbo", "SalesByCategory"), ["Seafood","1998"], maxrows=2)>>> for a in c.description:...  print a...('ProductName', -9, 40, None, None, None, 0)('TotalPurchase', 3, 17, None, 38, 2, 1)>>> for a in c.fetchall():...  print a...('Boston Crab Meat', 5318.0)('Carnarvon Tigers', 8497.0)>>> c.nextset()1>>> print c.fetchall()[(0,)]>>> print c.description[('@RETURN_VALUE', 4, -1, 4, 10, 0, 0)]>>>


    >>> c = db.cursor() # open the database as in the examples above>>> c.execute("create or replace function funcout (y out varchar2)return varchar2 is begin y := 'tested'; return 'returned'; end;")>>> params = [None]>>> c.callproc("funcout", params)>>> print params['tested']>>> print c.description[(None, 12.0, -1, None, None, None, 1)]>>> print c.fetchall()[('returned',)]>>>

    When finished, close the connections.

    >>> c.close()>>> db.close()>>>

    Standard extensions to the Python DB API

    • connection.dbname: Same as DatabaseMetaData.getDatabaseProductName
    • connection.dbversion:Same as DatabaseMetaData.getDatabaseProductVersion
    • cursor.updatecount: The value obtained from calling Statement.getUpdateCount
    • cursor.lastrowid: The value obtained from calling DataHandler.getRowId
    • cursor.tables(qualifier,owner,table,type): Same as DatabaseMetaData.getTables
    • cursor.columns(qualifier,owner,table,column): Same as DatabaseMetaData.getColumns
    • cursor.foreignkeys(primary_qualifier,primary_owner,pimary_table,foreign_qualifier,foreign_owner,foreign_table): Same as DatabaseMetaData.getCrossReference
    • cursor.primarykeys(qualifier,owner,table): Same as DatabaseMetaData.getPrimaryKeys
    • cursor.procedures(qualifier,owner,procedure): Same as DatabaseMetaData.getProcedures
    • cursor.procedurecolumns(qualifier,owner,procedure,column): Same as DatabaseMetaData.getProcedureColumns
    • cursor.statistics(qualifier,owner,table,unique,accuracy): Same as DatabaseMetaData.getIndexInfo

    Datatype mapping callbacks through DataHandler

    The DataHandler interface has three methods for handling type mappings. They are called at two different times, one when fetching and the other when binding objects for use in a prepared statement. I have chosen thisarchitecture for type binding because I noticed a number of discrepancies in how different JDBC drivers handled database types, in particular the additional types available in later JDBC versions.

    life cycle

    public void preExecute(Statement stmt) throws SQLException;A callback prior to each execution of the statement. If thestatement is a PreparedStatement (created when parameters are sent to the execute method), all the parameters will have been set.public void postExecute(Statement stmt) throws SQLException;A callback after successfully executing the statement. This is particularly useful for cases such as auto-incrementing columns where the statement knows the inserted value.

    developer support

    public String getMetaDataName(String name);A callback for determining the proper case of a name used in a DatabaseMetaData method, such as getTables(). This is particularly useful for Oracle which expects all names to be upper case.public PyObject getRowId(Statement stmt) throws SQLException;Acallback for returning the row id of the last insert statement.

    binding prepared statements

    public Object getJDBCObject(PyObject object, int type);This method is called when a PreparedStatement is created through use of the execute method. When the parameters are being bound to thestatement, the DataHandler gets a callback to map the type. This is only called if type bindings are present.public Object getJDBCObject(PyObject object);This method is called when no type bindings are present during the execution of a PreparedStatement.

    building results

    public PyObjectgetPyObject(ResultSet set, int col, int type);This method is called upon fetching data from the database. Given the JDBC type, return the appropriate PyObject subclass from the Java object at column col in the ResultSet set.

    callable statement support

    public PyObject getPyObject(CallableStatement stmt, int col, int type)throws SQLException;   This method is called upon fetching data from the database after   calling a stored procedure or function. Given the JDBC type, return   the appropriate PyObject subclass from the Java object at column   col in the CallableStatement.public void registerOut(CallableStatement statement, int index, intcolType, int dataType, String dataTypeName) throws SQLException;   This method is called to register an OUT or INOUT parameter on the   stored procedure. The dataType comes from java.sql.Types while the   dataTypeName is a vendor specific string.public String getProcedureName(PyObject catalog, PyObject schema,PyObject name);   This method is called to build a stored procedure's name.

    To get the desired outcome for your database driver, use thesecallbacks in a straightforward manner. Most of the time, nothing needs to be done in order to obtain the proper datatype mapping. The DataHandler callbacks should, however, offer a workaround when drivers deviate from the specification or treat values in a different way. Informix boolean example DataHandler.

    One such case where a driver needs a special mapping is Informix booleans. The are represented as the characters ‘t’ and ‘f’ in the database and have theirown type boolean. You can see from the example below, without the special DataHandler, the boolean type mapping fails.

    Jython 2.1b1 on java1.4.0-beta3 (JIT: null)Type "copyright", "credits" or "license" for more information.>>> from com.ziclix.python.sql import zxJDBC>>> zxJDBC.autocommit = 0>>> d, u, p, v = "database", "user", "password","com.informix.jdbc.IfxDriver">>> db = zxJDBC.connect(d, u, p, v)>>> c = db.cursor()>>> c.execute("create table g (a boolean)")>>> c.execute("insert into g values (?)", [1])Traceback (innermost last):File "<console>", line 1, in ?Error: No cast from integer to boolean. [SQLCode: -9634]>>> from com.ziclix.python.sql.informix import InformixDataHandler>>> c.datahandler = InformixDataHandler(c.datahandler)>>> c.execute("insert into g values (?)", [1], {0:zxJDBC.OTHER})>>>

    As you can see, the default handler fails to convert the Python 1 into an Informix boolean because the IfxDriver treats booleans as JDBC type OTHER. When the JDBC type is OTHER, the Python values can be interpreted by the InformixDataHandler as booleans because it is well-versed in the IfxDriver mappings.

    This functionality is also useful in handling the moreadvanced JDBC 2.0 types CLOB, BLOB and Array.

    You can also implement the DataHandler from within Jython as in this simple example:

    >>> class PyHandler(DataHandler):>>>  def __init__(self, handler):>>>   self.handler = handler>>>  def getPyObject(self, set, col, datatype):>>>   return self.handler.getPyObject(set, col, datatype)>>>  def getJDBCObject(self, object, datatype):>>>   print "handling prepared statement">>>   return self.handler.getJDBCObject(object, datatype)>>>>>> c.datahandler = PyHandler(c.datahandler)>>> c.execute("insert into g values (?)", [1])handling prepared statement>>>


    dbexts is a wrapper around DB API 2.0 compliant database modules. It currently supports zxJDBC and mxODBC but could easily be modified to support others. It allows developers to write scriptswithout knowledge of the implementation language of Python (either C or Java). It also greatly eases the burden of database coding as much of the functionality of the Python API is exposed through easier to use methods.

    Configuration file

    dbexts needs a configuration file in order to create a connection. The configurationfile has the following format:

    [default] name=mysql

    [jdbc] name=mysql url=jdbc:mysql://localhost/ziclix user= pwd= datahandler=com.ziclix.python.sql.handler.MySQLDataHandler

    [jdbc] name=ora url=jdbc:oracle:thin:@localhost:1521:ziclix user=ziclix pwd=ziclix driver=oracle.jdbc.driver.OracleDriver datahandler=com.ziclix.python.sql.handler.OracleDataHandler


    dbexts will default to looking for a file named ‘dbexts.ini’ in the same directory as but can optionally be passed a filename to the cfg attribute.

    __init__(self, dbname=None, cfg=None, resultformatter=format_resultset,autocommit=1)   The initialization method for the dbexts class. If dbname is None,   the default connection, as specified in the cfg file will be used.isql(self, sql, params=None, bindings=None, maxrows=None)   Interactively execute sql statement. If self.verbose is true, then   the results (if any) are displayed using the result formatting   method. If maxrows is specified, only maxrows are displayed.raw(self, sql, params=None, bindings=None, delim=None, comments=comments)   Executes the sql statement with params and bindings as   necessary. Returns a tuple consisting of (headers, results).schema(table, full=0, sort=1)   Displays the schema (indicies, foreign keys, primary keys and   columns) for the table parameter. If full is true, also compute   the exported (or referenced) keys. If sort is true (the default),   sort the column names.   >>> d.schema("store")   Table     store   Primary Keys     store_id {store_3}   Imported (Foreign) Keys     location (city.city_id) {store_7}   Exported (Referenced) Keys     store_id (site_store.store_id) {site_store_8}   Columns     location           int(4), non-nullable     store_id           serial(4), non-nullable     store_name         varchar(32), non-nullable   Indices     unique index {523_8115} on (store_id)     unique index {store_ix_1} on (store_name)   >>>table(table=None, types=("TABLE",), owner=None, schema=None)   If no table argument, displays a list of all tables. If a table   argument, displays the columns of the given table.proc(self, proc=None, owner=None, schema=None)   If no proc argument, displays a list of all procedures. If a proc   argument, displays the parameters of the given procedure.bcp(src, table, where='(1=1)', parameters=[], selective=[], ignorelist=[],   autobatch=0)   Bulk Copy from one database/table to another. The current instance   of dbexts is the source database to which the results of the query   on the foreign database will be inserted. An optional where clause   can narrow the number of rows to be copied.

    The following are generally not called since isql and raw can handle almost all cases.

    begin(self)Creates a new cursor.rollback(self)Rollback all the statementssince the creation of the cursor.commit(self, cursor=None, maxrows=None)Commit all the statements since the creation of the cursor.display(self)Display the results using the formatter.

    Example session

    Jython 2.1b1 on java1.4.0-beta3 (JIT: null)Type "copyright", "credits" or "license" for more information.>>> from dbexts import dbexts>>> d = dbexts()>>> d.isql("create table store (store_id int, store_name varchar(32),location int)")>>> d.isql("insert into store values (?, ?, ?)", [(1, "", 3),(2, "", 4)])>>> d.isql("insert into store values (?, ?, ?)", [(15, "", 1),(19, "", 3)])>>> d.isql("insert into store values (?, ?, ?)", [(5, "", 4)])>>> d.isql("select * from store order by store_name")STORE_ID | STORE_NAME  | LOCATION---------------------------------15       |     | 11        |  | 32        | | 419       |  | 35        |    | 45 rows affected>>>

    Additional Question — Can you convert Python to Java?

    Is Jython still used?

    Java. Jython was started by Jim Hugunin in 1997 as “JPython”, and has seen continued development since then. However, development of Jython is remains on the Python 2.7 line, a major release of the Python interpreter which, since the beginning of 2020, is no longer being maintained.

    Can Python use Java library?

    One of the most important features of Jython is its ability to import Java classes in a Python program. We can import any java package or class in Jython, just as we do in a Java program. The following example shows how the java.

    What is Jython used for?

    Jython is a version of the Python programming language that runs on the Java platform. It allows users to write programs in Python and compile them to Java bytecodes that run directly on a Java Virtual Machine, or JVM.

    How do you write a Jython script?

    Press [ to bring up the Script Editor.
    Select an example Jython script from the Templates › [by language] › Python menu.
    Press ⌃ Ctrl + R to run the script!

    What is difference between Python and Jython?

    Difference between Python and Jython Reference implementation of Python, called CPython, is written in C language. Jython on the other hand is completely written in Java and is a JVM implementation. Standard Python is available on multiple platforms. Jython is available for any platform with a JVM installed on it.

    How do I create a Jython file?

    You can create a new Jython script file, which you can then edit in the Jython editor. Creating Jython script files
    If necessary, create a project to contain the Jython script file.
    In the menu bar, select File > New > Other .
    Expand the Jython folder and select Jython Script File.

    Can we use pandas in Jython?

    You currently cannot use Pandas with Jython, because it depends on CPython specific native extensions. One dependency is NumPy, the other is Cython (which is actually not a native CPython extension, but generates such).

    How do I use Python in eclipse?

    Go to File → New → PyDev Project to start a wizard. In the next window that appears, enter the name of your project and select “python” and 3.0″; as the type. Make sure “create default ‘src’ folder and add it to the pythonpath?” is selected. Click Finish.

    How do I import a Python library into Jython?

    You can do the easy_install for jython. Then next time you startup jython you will be able to import it. The official docs are here:…

    What version of Python does Jython use?

    It was released on 21 March 2020 and is compatible with Python 2.7.

    How do you run a Python file with few arguments in Java?

    You can use Java Runtime. exec() to run python script, As an example first create a python script file using shebang and then set it executable. Hope this helps and if not then its recommended to join our Java training class and learn about Java in detail.

    Dannie Jarrod

    Leave a Comment