Gerald Bauer (Chairmain, CEO, CFO and CTO of Me, Myself & I, Inc.)
Java User Group (JUG) Austria Talk, February 2003
Python is a dynamic object-oriented scripting language created by Guido van Rossum in the early 90's to bridge the gap between shell and C programming. Python's elegant, easy to learn syntax, high-level data types, elaborate library, portability, and ease of extending and embedding in C/C++ all contribute to Python's popularity. Originally designed as an advanced scripting language, Python found new uses as a rapid application development language for web, database and GUI applications as well as for distributed systems and mobile code.
Jython is a 100 % Java version of the Python scripting language that allows you to compile Python scripts to Java byte code that runs on any Java Virtual Machine. Jython offers seamless and smoth Java intergration: from Python you can access all Java libraries, you can build applets or Java beans, you can derive from Java classes in Python and vice versa. Like Python, and unlike Java, you can use Jython interactively: just type in some Jython code at the prompt and see the story unfold immediately.
Scripting on the Rise. The Death of General Purpose Languages and Monolithic Applications.
Prefer the single-purpose languages below to general-purpose languages such as Java, C# or Shark.
Python does not replace Java. Python complements Java and doesn't compete head-on. Python is a scripting language. Java is a hard-core programming language (systems language).
new
, and more)Java
public class ServusAustria { public static void main( String args[] ) { System.out.println( "Servus Austria" ); } } |
Python
print 'Servus Austria' |
Java
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ServusAustria extends JFrame { public ServusAustria( String title ) { super( title ); addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent ev ) { exit(); } } ); JButton button = new JButton( "Servus Austria" ); button.setPreferredSize( new Dimension( 200, 50 ) ); button.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ev ) { exit(); } } ); getContentPane().add( button ); } public void exit() { System.exit( 0 ); } public static void main( String args[] ) { ServusAustria frame = new ServusAustria( "Python" ); frame.pack(); frame.show(); } } |
Python
import java.lang as lang import javax.swing as swing def exit( event ): lang.System.exit(0) frame = swing.JFrame( 'Python', windowClosing=exit ) button = swing.JButton( 'Servus Austria', preferredSize=(200,50), actionPerformed=exit ) frame.contentPane.add( button ) frame.pack() frame.show() |
Python + XUL
import java.lang as lang def exit( event ): lang.System.exit(0) |
<window title="Python" onclosing="exit()"> <button label="Servus Austria" style="width: 200; height: 50;" onclick="exit()" /> </window> |
>>> 2 + 2 4 >>> _ 4 >>> x = 4 >>> x * 2 8 >>> print 'Servus Austria' Servus Austria |
>>> import java.lang as lang >>> import javax.swing as swing >>> def exit( event ): ... lang.System.exit(0) ... >>> frame = swing.JFrame( 'Python', windowClosing=exit ) >>> frame javax.swing.JFrame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,ti tle=Python,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.s wing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmen tX=null,alignmentY=null,border=,flags=385,maximumSize=,minimumSize=,preferredSiz e=],rootPaneCheckingEnabled=true] >>> button = swing.JButton( 'Servus Austria', preferredSize=(200,50), actionPerf ormed=exit ) >>> button javax.swing.JButton[,0,0,0x0,invalid,layout=javax.swing.OverlayLayout,alignmentX =0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIRes ource@7df472,flags=296,maximumSize=,minimumSize=,preferredSize=java.awt.Dimensio n[width=200,height=50],defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=j avax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=tr ue,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSele ctedIcon=,selectedIcon=,text=Servus Austria,defaultCapable=true] >>> frame.contentPane.add( button ) javax.swing.JButton[,0,0,0x0,invalid,layout=javax.swing.OverlayLayout,alignmentX =0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIRes ource@7df472,flags=296,maximumSize=,minimumSize=,preferredSize=java.awt.Dimensio n[width=200,height=50],defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=j avax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=tr ue,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSele ctedIcon=,selectedIcon=,text=Servus Austria,defaultCapable=true] >>> frame.pack() >>> frame.show() |
It's object-oriented. Ideal for scripting (glueing together) components build in Java, C# or C++; easy reuse through classes, polymorphism, operator overloading and even multiple inheritance.
It's free. Open-Source; no restrictions on copying or adding Python to your app (Apache-style license)
It's portable. Written in portable ANSI C, compiles and runs anywhere (Linux, Mactionosh, Amiga, OS/2, VMS, QNX and many more); scripts compiled to portable bytecode run on any Python runtime
It's powerful. Simplicity and ease of use of a scripting language (Dynamic typing; Built-in object types; Extensive Libraries (=Batteries Included); Automatic Memory Management) along with programming in-the-large contructs (Modules, Classes, Exceptions)
It's mixable. Extend Python with components in C, C++ or Java; embed Python into your app and call it from C, C++ or Java; Python supports COM on Windope
It's easy to use. Easy syntax (no curly braces, no semicolons, dynamic typing and so on); high-level built-in types (lists, maps, big numbers, and more)
It's easy to learn. Get started in days (or if you're already an experienced pro in hours); programming for everyone
It's interactive. Create, view or change objects at run-time on the fly; no compile and link steps; instand turnaround .
It's robust. Exception handling; Automatic Memory Management (=Garbage Collection); Dynamic Type Checking; No Unsafe Pointers
It's dynamic. "Late-Binding" Lanuage; Add Methods At Runtime; Call Methods Using Reflection
Java
List list = new LinkedList(); list.add( new Integer( 1 ) ); list.add( new Integer( 2 ) ); list.add( new Integer( 3 ) ); |
Python
list = [1, 2] list.append( 3 ) |
Java
Map map = new HashMap(); map.put( "one", new Integer( 1 ) ); map.put( "two", new Integer( 2 ) ); map.put( "three", new Integer( 3 ) ); System.out.println( map.get( "one" ) ); |
Python
map = { "one" : 1, "two" : 2, "three" : 3 } print map[ "one" ] |
Java
double sum = 0.0; for( Iterator it=nums.iterator(); it.hasNext() ) { sum += ((Double)it.next()).doubleValue(); } |
Python
sum = 0.0 for x in nums: sum = sum + x |
Java
JFrame frame = new JFrame( "Servus" ); frame.setSize( new Dimension( 200, 200 ) ); frame.setVisible( true ); |
Python
frame = JFrame( "Servus", visible=1, size=(200,200) ) |
Java
double x = 10000.0 / 3.0; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumFractionDigits( 2 ); nf.setMaximumFractionDigits( 2 ); String s = nf.format( x ); for( int i = s.length(); i < 10; i++ ) System.out.print( ' ' ); System.out.print( s ); |
Python
x = 10000.0 / 3.0 print "%10.2f" % x |
Java | Python |
---|---|
"\\$\\d+,\\d+\\."
|
r'\$\d+,\d+\.'
|
"\\s((::)(\\w+))\\b"
|
r'\s((::)(\w+))\b'
|
"c:\\sandbox\\doc\\talk"
|
r'c:\sandbox\doc\talk'
|
"Christina says, \"Python Rocks\""
|
'Christina says, "Python Rocks"'
|
Basic Data Types
Java | Python | Comments |
---|---|---|
boolean
|
Python has no boolean type yet. Python uses 1 for true, and 0 or any empty string, list or map as false. | |
char
|
string
|
Python uses a string of length 1 as a character. |
byte , short , int
|
int
|
|
long
|
long
|
Python longs are unbound (like Java's BigInteger ). |
float , double
|
float
|
Python floats use the same precision as Java doubles. |
complex
|
Python has built-in support for complex numbers
e.g. 3.5+1.2j or 2.0J
|
More Data Types
Java | Python | Comments |
---|---|---|
java.lang.String
|
string
|
|
java.util.List
|
list
|
Python has built-in support for lists e.g. [1, 2]
|
java.util.Map
|
dictonary
|
Python has built-in support for maps e.g. { "one" : 1, "two" : 2 }
|
Logical Operators. Python tends to use English words for its logical operators instead of symbols.
Java | Python | Comments |
---|---|---|
&&
|
and
|
|
||
|
or
|
|
!
|
not
|
|
==
|
is
|
Test for identical object identity. |
equals()
|
==
|
Test for same value. |
x < y && y < z
|
x < y < z
|
Python supports chained comparisons. |
Arithmetic Operators. Python use the same operators as Java with some exceptions:
++
) and decrement (--
) operator.<<<
and >>>
).**
operator for raising a number to a powerExamples
(-1+2)*3/4**5 0 < x <= 5 1 << 16, x & 0xff, x|1, ~x, x^y 1j**2 |
if
Conditionals
|
|
for
Loop
|
|
||
|
|
while
Loop
|
|
Exception Handling
|
|
||
|
|
||
|
|
Java
import java.applet.*; public class Servus extends Applet { public void paint( Graphics g ) { g.drawString( "Servus Applet", 10, 10 ); } } |
Python
from java.applet import Applet class Servus( Applet ): def paint( self, g ): g.drawString( "Servus Applet" ) |
Java
import java.io.*; import javax.servlet.*; public class Hello extends HttpServlet { public void doGet( HttpServletRequest request, HttpServletResponse response ) { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); out.println( "<html>" + "<head><title>Servus Servlet</title></head>" + "<body>Servus Servlet at " + new Date() + "</body>" + "</html>" ); } } |
Python
import java, javax, sys class hello( javax.servlet.http.HttpServlet ): def doGet( self, request, response ): response.contentType = "text/html" out = response.outputStream print >> out, """<html> <head><title>Servus Servlet</title></head> <body>Servus Servlet at %s</body> </html> """ % java.util.Date() |
Python Class
class DynProps: def __init__( self, **args ): self.props = args def __getattr__( self, attribute ): return self.props[ attribute ] |
Usage Example
>>> capital = DynProps( austria="vienna", canada="ottawa" ) >>> print capital.austria vienna >>> print capital.canada ottawa >>> capital.props[ "peru" ] = "lima" >>> print capital.peru lima |
import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main( String args[] ) throws PyException { // create a phyton interpreter PythonInterpreter interp = new PythonInterpreter(); // execute a statement interp.exec( "import sys" ); interp.exec( "print sys" ); // create a int variable n with the value 7 interp.set( "n", new PyInteger( 7 )); // print value of n interp.exec( "print n" ); // assign value to new variable x interp.exec( "x = 2+2" ); PyObject x= interp.get( "x" ); // print value of x System.out.println( "x: " + x ); } } |
Python. Macro Doubles Text in Notepad (e.g. Hello becomes Hello Hello)
allText = textEditor.getText() allText = allText + allText textEditor.setText( allText ) |
Java. Code For Running Python Macro.
PythonInterpreter interp = new PythonInterpreter(); interp.exec( "from javax.swing.text import JTextComponent" ); interp.set( "textEditor", getEditor() ); for( Iterator it=scriptLines.iterator(); it.hasNext(); ) { String line = (String) it.next(); System.out.println( "[Script] " + line ); interp.exec( line ); } |
jythonc
jythonc
lets you compile (=freeze) Python scripts
to stand-alone Java bytecode (that is,
.class
files).
Why? You can use Python scripts compiled to plain-vanilla Java classes as applets, Java beans and so on and distribute your frozen Python scripts in jars.
Usage Examples
Compile all applet Python script examples and
pack them up in appletdemo.jar
jythonc --core --deep --jar appletdemo.jar *.py |
Create a sekeleton class to allow usage of a Python class
in a Java GUI (as a java.awt.Component
)
jythonc Graph.py |
Compiler Options Sampling
Option | Description |
---|---|
--package package
|
Put all compiled code into the named Java package. |
--addpackages packages
|
Include Java dependencies from this list of packages. |
--core
|
Include the core Python libraries. |
--all
|
Include all of the Python libraries (that is, everything in core plus compiler and parser). |
--bean jar
|
Compile into jar, include manifest for bean. |
--workdir directory
|
Specify working directory for compiler (default is ./jpywork ) |
--compileropts options
|
Options passed directly to the Java compiler.
Alternatively, you can set the property
python.jpythonc.compileropts in the registry. |
Some Statistics
Tcl. Jacl (Java Command Language) is a free, open-source Tcl 8.x scripting interpreter in 100 % Java initially created by Sun Labs in 1998 and now headed Mo DeJong . Jon Ousterhout created Tcl in the late 80's as an embeddable command language for interactive Unix tools. More Info at http://www.tcl.tk/software/java/
JavacScript. Rhino is a free, open-source Mozilla-licensed Javascript engine in 100 % Java. Netscape started work on Rhino in Fall 1997 for the now defunct "Javagator". More Info at http://www.mozilla.org/rhino/
Dynamic Java / Java Lite. BeanShell is a free, open-source, small (~175k) scripting interpreter in 100 % Java that runs standard Java statements and expressions and also sports a dynamically typed, casting optional Java lite syntax. Headed by Patrick Niemeyer. More Info at http://www.beanshell.org
Ruby. JRuby is a free, open-source Ruby interpreter in 100 % Java that you can easily add to your app to script any Java class. More Info at http://jruby.sourceforge.net
Rexx. NetRexx is a 100 % Java interpreter for a Rexx dialect created by Mike Cowlishaw, the Rexx inventor. Mike Cowlishaw created Rexx in 1979 for simplifying programming tasks on IBM's CMS timesharing system. More Info at http://www2.hursley.ibm.com/netrexx/
Smalltalk. Bistro is a free, open-source variant of Smalltalk in 100 % Java than runs on any Java Virtual Machine. Bistro mixes the best of Smalltalk and Java. More Info at http://bistro.sourceforge.net
Scheme. Skij is small Scheme interpreter in 100 % Java with extension to interactively create, view or change any Java object at run-time. (Scheme is a modern variant of Lisp.) More Info at http://alphaworks.ibm.com/tech/Skij
And Many More (Lua, Basic, and so on and on). See Robert Tolksdorf's list of programming languages for the Java Virtual Machine for more.
Bonus: Beanshell (bsh) Scripting Example
foo = "Foo"; four = (2 + 2)*2/2; // print is a built-in bean shell (bsh) command print( foo + " = " + four ); // do a loop for( i=0; i<5; i++ ) print( i ); // popup a frame with a button button = new JButton( "Hello" ); frame = new JFrame( "Bean Shell" ); frame.getContentPane().add( button ); frame.pack() frame.show() // scripted method add( a, b ) { return a + b; } |
Feature | Python | Tcl | Perl | Java Script | Ruby | Visual Basic | |
---|---|---|---|---|---|---|---|
Speed of use | Rapid development | ||||||
Flexible, rapid evolution | |||||||
Great regular expressions | |||||||
Breadth of functionality | Easily extensible | ||||||
Embeddable | |||||||
Easy GUIs | |||||||
Internet and Web-enabled | |||||||
Enterprise usage | Cross platform | ||||||
Internationalization support | |||||||
Thread safe | |||||||
Database access |
Source: http://www.tcl.tk/advocacy
Python supports programming in-the-large
Feature | Benefits |
---|---|
No compile or link steps | Rapid development cycle turnaround |
No type declarations | Simpler, shorter, and more flexible programs |
Automatic memory management | Garbage collection avoids bookkeeping code |
High-level datatypes and operations | Fast development using built-in object types |
Object-oriented programming | Code reuse, C++, Java, and COM integration |
Embedding and extending in C | Optimization, customization, system "glue" |
Classes, modules, exceptions | Modular "programming-in-the-large" support |
A simple, clear syntax and design | Readability, maintainability, ease of learning |
Dynamic loading of C modules | Simplified extensions, smaller binary files |
Dynamic reloading of Python modules | Modify programs without stopping |
Universal "first-class" object model | Fewer restrictions and special-case rules |
Runtime program construction | Handles unforeseen needs, end-user coding |
Interactive, dynamic nature | Incremental development and testing |
Access to interpreter information | Metaprogramming, introspective objects |
Wide interpreter portability | Cross-platform programming without ports |
Compilation to portable bytecode | Execution speed, protecting source code |
Standard portable GUI toolkit | Tkinter scripts run on X, Windows, and Macs |
Standard Internet protocol support | Easy access to email, FTP, HTTP, CGI, etc. |
Standard portable system calls | Platform-neutral system scripting |
Built-in and third-party libraries | Vast collection of precoded software components |
True open-source software | May be freely embedded and shipped |
Source: Programming Python, Mark Lutz
${bookmarks.rows.title}
Jelly Script
<j:jelly xmlns:j="jelly:core"> <j:choose> <j:when test="${user.locale}=='de_AT'"> Servus ${user.name} </j:when> <j:otherwise> Hello ${user.name} </j:otherwise> </j:choose> </j:jelly> |
Jelly Script
<babelfish:translate from="en" to="fr"> Welcome ${user.name} to Jelly </babelfish:translate> |
Output
<xul> <menubar id="MAIN"> <menu label="Bookmarks"> <menuitem label="Luxor XUL Home Page" href="http://luxor-xul.sourceforge.net" /> <menuitem label="Mozilla XUL Home Page" href="http://www.mozilla.org/xpfe/" /> <menuitem label="Mozilla XUL Reference" href="http://www.mozilla.org/xpfe/xulref" /> <menuitem label="XUL Tutorial" href="http://www.xulplanet.com/tutorials/xultu/" /> </menu> </menubar> </xul> |
Jelly Script
<j:jelly xmlns:j="jelly:core" xmlns:sql="jelly:sql"> <sql:setDataSource url="jdbc:hsqldb:." driver="org.hsqldb.jdbcDriver" user="sa" password="" /> <sql:query var="results"> SELECT TITLE, HREF FROM BOOKMARK </sql:query> <xul> <menubar id="MAIN"> <menu label="Bookmarks"> <j:forEach items="${results.rowsByIndex}" var="row"> <menuitem label="${row[0]}" href="${row[1]}" /> </j:forEach> </menu> </menubar> </xul> </j:jelly> |
Library | Description |
---|---|
core | Core tags from the JSTL (Java Server Pages Standard Tag Library) |
xml | XML tags from the JSTL |
sql | SQL tags from the JSTL |
ant | A tag library that lets you use Ant tasks within Jelly |
log | A tag library that lets you create logging infos for log4j, Java 1.4 java.util.logging and other logging toolkits |
http | A tag library that lets you perform GET, POST and other HTTP actions |
html | A tag library that lets you parse HTML and process it XML-style using XPath expressions and more |
junit | A tag library that lets you write or fire off unit tests |
and many more
Projects | Description |
---|---|
Maven | Project Management tool built on top of Ant |
Latka | Functional (end-to-end) testing tool in Java using an XML syntax to define a series of HTTP requests and set of checks for verify error-free processing |
Luxor | Coming Soon; XUL toolkit in Java; lets you build UIs using XML |
Jython / Python for Java
Jython Essentials by Samuele Pedroni and Noel Rappin, 304 pages, O'Reilly, ISBN: 0596002475, (March 2002) | |
Python Programming with the Java Class Libraries by Richard Hightower, 640 pages, Addison-Wesley, ISBN: 0201616165, (June 2002) |
Python General
Practical Python by Magnus Lie Hetland, 648 pages, Apress, ISBN: 1590590066, (August 2002) | |
Core Python by Wesley J. Chun, 816 pages, Prentice Hall, ISBN: 0130260363, (December 2000) | |
Learning Python by Mark Lutz and David Ascher, 366 pages, O'Reilly, ISBN: 1565924649, (May 1999) | |
Python Cookbook by Alex Martell and David Ascher, 606 pages, O'Reilly, ISBN: 0596001673, (July 2002) | |
Python in a Nutshell by Alex Martelli, 600 pages, O'Reilly, ISBN: 0596001886, (March 2003) |
and many more
Official Python Site
http://www.python.org
Python Tutorial
http://www.python.org/doc/current/tut/tut.html
Python FAQ
http://www.python.org/doc/FAQ.html
Python Language Reference
http://www.python.org/doc/current/ref/ref.html
Python Library Reference
http://www.python.org/doc/current/lib/lib.html
Official Jython Site
http://www.jython.org
Tips for Scripting Java with Jython
http://www.oreillynet.com/pub/a/onjava/2002/03/27/jython.html
by Noel Rappin, O'Reilly Network, March 2002
Jython Typs for Python Programmers
http://www.oreillynet.com/pub/a/python/2002/04/11/jythontips.html
by Noel Rappin, O'Reilly Network, April 2002
Introduction to Jython
http://www.oreilly.com/catalog/jythoness/chapter/ch01.html
by Samuele Pedroni and Noel Rappin, Sample Chapter 1 from Jython Essentials Book, O'Reilly, 2002
JPython: The Felicitous Union of Python and Java
http://www.oreilly.com/catalog/lpython/chapter/ch10_fel.html
by Mark Lutz and David Ascher, Sample Chapter 10 from Learning Python Book, O'Reilly, 1999
Daily Python URL
http://www.pythonware.com/daily
Guido Van Rossum Talks
http://www.python.org/doc/essays/ppt/
Introduction to Python @ Linux World 2002, State of the Python Union @ OSCON 2002, And Many More
Scripting for Java: Paradigms for the 21st Century
http://servlet.java.sun.com/javaone/sf2002/conf/sessions/display-2609.en.jsp
by Dana Moore and Bill Wright (BBN Technologies), JavaOne 2002, 50 slides, includes lots of real-world examples
such as
O'Reilly Network Python Dev Center
http://www.onlamp.com/python
Paper by John K. Ousterhout, Father of Tcl/Tk, published in IEEE Computer in March 1998
Scripting Is On The Rise; Different Tools for Different Tasks
Scripting languages and system programming languages are complementary, and most major computing platforms since the 60's have provided both kinds of languages. The languages are typically used together in component frameworks, where components are created with system programming languages and glued together with scripting languages. However, serveral recent trends, such as faster machines, better scripting languages, the increasing importance of graphical user interfaces and component architectures, and the growth of the Internet, have greatly increased the applicability of scripting languages.
Full story at http://home.pacbell.net/ouster/scripting.html