Howto package Jython for Java WebStart/Applets

It's nice to use jython especially if you don't quite know what kind of computation you need to do or what kind of UI layout might be good... and jyhton is much easier on the eye than some XML markup ... or even a GUI builder.

But once part of your program is in jython how to you (easily) deliver it to the masses? Here we start with packaging a jython program for use with java webstart, later we'll look at other packaging options. Here is the Launcher : . And here is the (very simple) jython code we a going to turn into this webstart program (
import sys
# this is essestial
# fire up the java console to see this output
print sys.path
print sys.argv
# os is partially python code
import os
# smtplib is our "non-trivial" python library using the socket library etc.
import smtplib
from java import awt
from java.lang import Runnable
from javax import swing

def doemail(address,msg):
        subject='Hello from the jython app' 
        headers='From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n' % (frm,to,subject)
            msguser('email sent!')

def sendmail(e):
    if email.text:
    	msguser('input an email address first')
def msguser(msg):
def exit(): raise SystemExit

def run():
    frame=swing.JFrame('A Jython swing app',windowClosing=lambda e:exit())
    label=swing.JLabel('enter your email:',labelFor=email)

    button = swing.JButton("send",actionPerformed=lambda e:sendmail(e))

    frame.bounds = (200,200,400,400)
    frame.visible = 1

class R(Runnable):
    def run(self): run()

# okay just run ....
We place this file in a directory called mypkg and add a to turn it into a "package". Here is the important fragment of the jnlp file that is used to kick-off the webstart
<?xml version="1.0" encoding="utf-8"?>
    <title>Jython Launcher</title>
    <vendor>Computational Systems Biology</vendor>
    <homepage href="" />
    <description>JythonLauncher Application</description>
    <icon               href=""/>
    <icon kind="splash" href=""/>
    <shortcut online="false">
      <menu submenu="Computational Systems Biology"/>
    <related-content href="" >
	   <description>This product is licensed under a Creative Commons License</description>
	   <icon href="" />

<resources> <j2se version="1.5+"/> <!-- turn this part into a resource --> <jar href="" part="jython" /> <jar href="" part="jython-lib" download="eager" /> <!-- see below --> <jar href="" download="eager" /> <package name="org.python.*" part="jython" recursive="true" /> <package name="com.ziclix.python.sql.*" part="jython" recursive="true" /> <jar href="mypkg.jar" part="jython-code" download="eager" /> <!-- <property name="python.cachedir" value="${user.home}/.jythonhome/cachedir" /> --> </resources> <application-desc main-class="org.python.util.jython"> <argument>-c</argument> <argument>from mypkg import run</argument> </application-desc>
This small test has 3 resources. The jython jar file, a jar of the "Lib" directory and a jar of the jython "program" you have written. (Notice too that they don't have to reside in the same directory... I have placed my jython.jar etc. jarfiles at a URL managed by a JnlpDownloadServlet to take advantage of the extra compression available with this servlet)

Packaging the Python Library

Package the Python Library. We remove all tests but you could go further since the resulting jar file for jython 2.5.1 is 3.9Mb! Do we really need all those encodings?
    cp -R `jython -c 'import sys;print sys.prefix'`/Lib . # make a local copy
    # remove any "test" code
    /bin/rm -rf Lib/distutils Lib/test Lib/email/test # remove all tests - there's a lot!
    find Lib -name '*test*' -exec rm -f {} \; # plus anything that looks like a test!
    find Lib -name '*tests*' -exec rm -f {} \;
    @jython -c 'from compileall import main; main()' -d Lib Lib # now compile
    # get rid of python now
    find Lib -name '*.py' -exec rm -f {} \; # don't need the *.py files
    ${JAVA_HOME}/bin/jar cvf jythonlib.jar Lib
    /bin/rm -rf Lib

Signing your jar files

Because of code like this in the startup of PySystemState() constructor:

currentWorkingDir = new File("").getAbsolutePath();
You will get a access denied (java.util.PropertyPermission user.dir read) exception unless all your jar files are signed. Sigh! Thus it is impossible at the moment to use jython in a applet (since the demise of jythonc at least). Happily it's not too hard to "sign" a jar once you have keystore

${JDK_HOME}/bin/jarsigner --keystore ${key.storefile} --storepass ${key.storepass}  \
	--keypass ${key.storepass}  jarfile-to-sign  ian.castleden
Of course you have to create a keystore file... which is a real pain (Of course once you have created it you can reuse it again and again....).
${JDK_HOME}/bin/keytool -genkey -keystore ${key.storefile} -keypass ${key.storepass} -storepass ${key.storepass} \ 
	-validity 3650 -keyalg RSA -alias ian.castleden \
	-dname ", OU=Computational Systems Biology, O=CPEB, L=Perth, ST=Western Australia, C=AU"
There is even an ANT Task to help:
    <target name="makeKeyStore">
    	<delete file="${key.storefile}"/>
    	<genkey keystore="${key.storefile}" keypass="${key.pass}"
    	   validity="3650" storepass="${key.storepass}" keyalg="RSA"
    	   alias="ian.castleden" verbose="true">   	
               <param name="CN" value=""/>
               <param name="OU" value="Computational Systems Biology"/>
               <param name="O"  value="Plant Energy Biology"/>
               <param name="L"  value="Perth"/>
               <param name="ST" value="Western Australia"/>
               <param name="C"  value="AU"/>
It is easiest if everything goes into a python package... say mypkg. Here is Makefile fragment that creates mysql.jar.
    @jython -c 'from compileall import main; main()' mypkg/
    jar cvf mypkg.jar mypkg/
    ${JDK_HOME}/bin/jarsigner --keystore ${key.storefile} --storepass ${key.storepass}  \
	--keypass ${key.storepass}  mypkg.jar  ian.castleden

Dealing with resources

One may have to package resources such as "icons" or configuration files. How does one reference them once they are in a jarfile? At first I thought something like this might work even though you have to supply the name of the jarfile "by hand"
from import URL
def findurl(jarfile):
    import re
    if _m:
        U='jar:file:%s!/%s/' % (jarfile,
        def mkurl(png): return URL(U+png)
        def mkurl(png): return URL('file:'+U+os.sep+png)
    return mkurl

def icon(png):
    png += '.png'
    return swing.ImageIcon(url)
This does indeed work for example when launching from a shell where the jarfile is indeed mypkg.jar
exec java -cp mypkg.jar:${JNLP}/jython2.5.1.jar:${JNLP}/jythonlib2.5.1.jar org.python.util.jython -c 'from mypkg import run' "$@"
But not from java webstart where the jarfile has some mangled name. After fruitlessly trying to get hold of the class loader used to load the jython code - in jython - I created a small wrapper (that could easily go into the jython codebase :) to do it for me.
package org.ce4csb.python;
// maybe package org.python.util ?;

import org.python.core.ClasspathPyImporter;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.util.FileUtil;

public class ChromeLoader {
	/** uses the ClasspathPyImporter classLoader to 
	 * load this resource. Objects packaged up for as *.py or their
	 * class equivalents are extracted using this loader. We do the samething
	 * for other object jar'ed with them
	 * @param chrome the object image file/document to load
	 * @return input stream of object or null
	public static InputStream load(String chrome) {
		ClassLoader loader = ClasspathPyImporter.class.getClassLoader();
		if (loader != null) {
			return loader.getResourceAsStream(chrome);
		return null;
	public static URL findURL(String chrome) {
		ClassLoader loader = ClasspathPyImporter.class.getClassLoader();
		if (loader != null) {
			return loader.getResource(chrome);
		return null;
	public static byte[] loadBytes(String chrome) throws IOException {
		InputStream input = load(chrome);
		if (input == null) { return null; }
		return FileUtil.readBytes(input);
	public static PyObject loadAsFile(String chrome) {
		InputStream input = load(chrome);
		if (input == null) { return Py.None; }
		return FileUtil.wrap(input);
With this class one can get at resources with has:
def findurl():
    import re
    if _m:
        from org.ce4csb.python import ChromeLoader
        def mkurl(png): return ChromeLoader.findURL(PKG + '/'+ png)
    	from import URL
        def mkurl(png): return URL('file:'+PKG+os.sep+png)
    return mkurl

def icon(png):
    png += '.png'
    return swing.ImageIcon(mkurl(png))


Where does jython under webstart store its cachedir?
logos The Government of Western Australia The University of Western Australia Australian Research Council Centre of Excellence in Plant Energy Biology