Jython – Modules

Jython – Modules ”; Previous Next A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it. In the following code (hello.py) a function SayHello() is defined. #definition of function defSayHello(str): print “Hello “, str return To use the SayHello() function from another script, import the hello.py module in it. import hello hello.SayHello(“TutorialsPoint”) However, this will import all functions defined in the module. In order to import specific function from module use following syntax. from modname import name1[, name2[,… nameN] For example, to import only the SayHello() function, change the above script as follows. from hello import SayHello SayHello(“TutorialsPoint”) There is no need to prefix the name of the module while calling the function. Print Page Previous Next Advertisements ”;

Jython – JDBC

Jython – JDBC ”; Previous Next Jython uses the zxJDBC package that provides an easy-to-use Python wrapper around JDBC. zxJDBC bridges two standards: JDBC is the standard platform for database access in Java, and DBI is the standard database API for Python apps. ZxJDBC provides a DBI 2.0 standard compliant interface to JDBC. Over 200 drivers are available for JDBC and they all work with zxJDBC. High performance drivers are available for all major relational databases, including − DB2 Derby MySQL Oracle PostgreSQL SQLite SQL Server and Sybase. The ZxJDBC package can be downloaded from https://sourceforge.net/projects/zxjdbc/ or http://www.ziclix.com/zxjdbc/. The downloaded archive contains the ZxJDBC.jar, which should be added to the CLASSPATH environment variable. We intend to establish database connectivity with MySQL database. For this purpose, the JDBC driver for MySQL is required. Download the MySQL J connector from the following link – https://dev.mysql.com/downloads/connector/j/ and include the mysql connector java-5.1.42-bin.jar in the CLASSPATH. Login to the MySQL server and create a student table in the test database with the following structure − Field Type Width Name Varchar 10 Age Int 3 Marks Int 3 Add a few records in it. Name Age Marks Ravi 21 78 Ashok 20 65 Anil 22 71 Create the following Jython script as dbconnect.py. url = “jdbc:mysql://localhost/test” user = “root” password = “password” driver = “com.mysql.jdbc.Driver” mysqlConn = zxJDBC.connect(url, user, password, driver) mysqlConn = con.cursor() mysqlConn.execute(“select * from student) for a in mysql.fetchall(): print a Execute the above script from the Jython prompt. Records in the student table will be listed as shown below − (“Ravi”, 21, 78) (“Ashok”, 20, 65) (“Anil”,22,71) This explains the procedure of establishing JDBC in Jython. Print Page Previous Next Advertisements ”;

Jython – Functions

Jython – Functions ”; Previous Next A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement. Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear. #definition of function defSayHello(): “optional documentation string” print “Hello World” return #calling the function SayHello() A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception. Example Live Demo #defining function with two arguments def area(l,b): area = l*b print “area = “,area return #calling function length = 10 breadth = 20 #with two arguments. This is OK area(length, breadth) #only one argument provided. This will throw TypeError area(length) The output will be as follows − area = 200 Traceback (most recent call last): File “area.py”, line 11, in <module> area(length) TypeError: area() takes exactly 2 arguments (1 given) After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function. Live Demo #defining function def area(l,b): area = l*b print “area = “,area return area #calling function length = 10 breadth = 20 #calling function and obtaining its reurned value result = area(length, breadth) print “value returned by function : “, result The following output is obtained if the above script is executed from the Jython prompt. area = 200 value returned by function : 200 Print Page Previous Next Advertisements ”;

Jython – Layout Management

Jython – Layout Management ”; Previous Next Layout managers in Java are classes those, which manage the placement of controls in the container objects like Frame, Dialog or Panel. Layout managers maintain the relative positioning of controls in a frame, even if the resolution changes or the frame itself is resized. These classes implement the Layout interface. The following Layout managers are defined in the AWT library − BorderLayout FlowLayout GridLayout CardLayout GridBagLayout The following Layout Managers are defined in the Swing library − BoxLayout GroupLayout ScrollPaneLayout SpringLayout We shall use AWT layout managers as well as swing layout managers in the following examples. Absolute Layout Flow Layout Grid Layout Border Layout Box Layout Group Layout Let us now discuss each of these in detail. Absolute Layout Before we explore all the above Layout managers, we must look at absolute positioning of the controls in a container. We have to set the layout method of the frame object to ‘None’. frame.setLayout(None) Then place the control by calling the setBounds() method. It takes four arguments – x position, y position, width and height. For example – To place a button object at the absolute position and with the absolute size. btn = JButton(“Add”) btn.setBounds(60,80,60,20) Similarly, all controls can be placed by properly allocating position and size. This layout is relatively easy to use, but fails to retain its appearance when the window either is resized, or if the program is executed when screen resolution changes. In the following Jython script, three Jlabel objects are used to display text “phy”, “maths” and “Total” respectively. In front of these three – JTextField objects are placed. A Button object is placed above the “Total” label. First of all the JFrame window is created with a layout set to none. frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) Then different controls are added according to their absolute position and size. The complete code is given below − from javax.swing import JFrame, JLabel, JButton, JTextField frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) lbl1 = JLabel(“Phy”) lbl1.setBounds(60,20,40,20) txt1 = JTextField(10) txt1.setBounds(120,20,60,20) lbl2 = JLabel(“Maths”) lbl2.setBounds(60,50,40,20) txt2 = JTextField(10) txt2.setBounds(120, 50, 60,20) btn = JButton(“Add”) btn.setBounds(60,80,60,20) lbl3 = JLabel(“Total”) lbl3.setBounds(60,110,40,20) txt3 = JTextField(10) txt3.setBounds(120, 110, 60,20) frame.add(lbl1) frame.add(txt1) frame.add(lbl2) frame.add(txt2) frame.add(btn) frame.add(lbl3) frame.add(txt3) frame.setVisible(True) The output for the above code is as follows. Jython FlowLayout The FlowLayout is the default layout manager for container classes. It arranges control from left to right and then from top to bottom direction. In following example, a Jlabel object, a JTextField object and a JButton object are to be displayed in a JFrame using FlowLayout manager. To start with, let us import the required classes from the javax.swing package and the java.awt package. from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import FlowLayout Then create a JFrame object and set its Location as well as the size properties. frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(200,200) Set the layout manager for the frame as FlowLayout. frame.setLayout(FlowLayout()) Now declare objects for JLabel, JTextfield and JButton classes. label = JLabel(“Welcome to Jython Swing”) txt = JTextField(30) btn = JButton(“ok”) Finally add these controls in the frame by calling the add() method of the JFrame class. frame.add(label) frame.add(txt) frame.add(btn) To display the frame, set its visible property to true. The complete Jython script and its output is as given below − from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import FlowLayout frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(200,200) frame.setLayout(FlowLayout()) label = JLabel(“Welcome to Jython Swing”) txt = JTextField(30) btn = JButton(“ok”) frame.add(label) frame.add(txt) frame.add(btn) frame.setVisible(True) Jython GridLayout The Gridlayout manager allows placement of controls in a rectangular grid. One control is placed in each cell of the grid. In following example, the GridLayout is applied to a JFrame object dividing it in to 4 rows and 4 columns. A JButton object is to be placed in each cell of the grid. Let us first import the required libraries − from javax.swing import JFrame, JButton from java.awt import GridLayout Then create the JFrame container − frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,400) Now, apply GridLayout by specifying its dimensions as 4 by 4. frame.setLayout(GridLayout(4,4)) We should now use two FOR loops, each going from 1 to 4, so sixteen JButton objects are placed in subsequent cells. k = 0 frame.setLayout(GridLayout(4,4)) for i in range(1,5): for j in range(1,5): k = k+1 frame.add(JButton(str(k))) Finally set visibility of frame to true. The complete Jython code is given below. from javax.swing import JFrame, JButton from java.awt import GridLayout frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,400) frame.setLayout(GridLayout(4,4)) k = 0 for i in range(1,5): for j in range(1,5): k = k+1 frame.add(JButton(str(k))) frame.setVisible(True) The output of the above code is as follows − Jython BorderLayout The BorderLayout manager divides the container in five geographical regions and places with one component in each region. These regions are represented by defined constants as follows − BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.CENTER Let us consider the following example − Jython BoxLayout The BoxLayout class is defined in the javax.swing package. It is used to arrange components in the container either vertically or horizontally. The direction is determined by the following constants − X_AXIS Y_AXIS LINE_AXIS PAGE_AXIS The integer constant specifies the axis along which the container”s components should be laid out. When the container has the default component orientation, LINE_AXIS specifies that the components be laid out from left to right, and PAGE_AXIS specifies that the components be laid out from top to bottom. In the following example, panel (of JPanel class) is added in a JFrame object. Vertical BoxLayout is applied to it and two more panels, top and bottom, are added to it. These two internal panels have two buttons each added in the horizontal Boxlayout. Let us first create the top-level JFrame window. frame = JFrame() frame.setTitle(“Buttons”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(300, 150) The JPanel object is declared having a vertical BoxLayout. Add it in top-level frame. panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) frame.add(panel) In this panel, two more panels top and bottom are added

Jython – Overview

Jython – Overview ”; Previous Next Jython is the JVM implementation of the Python programming language. It is designed to run on the Java platform. A Jython program can import and use any Java class. Just as Java, Jython program compiles to bytecode. One of the main advantages is that a user interface designed in Python can use GUI elements of AWT, Swing or SWT Package. Jython, which started as JPython and was later renamed, follows closely the standard Python implementation called CPython as created by Guido Van Rossum. Jython was created in 1997 by Jim Hugunin. Jython 2.0 was released in 1999. Since then, Jython 2.x releases correspond to equivalent CPython releases. Jython 2.7.0 released in May 2015, corresponds to CPython 2.7. Development of Jython 3.x is under progress. Difference between Python and Java Following are the differences between Python and Java − Python is a dynamically typed language. Hence, the type declaration of variable is not needed. Java on the other hand is a statically typed language, which means that the type declaration of variable is mandatory and cannot be changed. Python has only unchecked exceptions, whereas Java has both checked and unchecked exceptions. Python uses indents for scoping, while Java uses matching curly brackets. Since Python is an interpreter-based language, it has no separate compilation steps. A Java program however needs to be compiled to bytecode and is in turn executed by a JVM. Python supports multiple inheritance, but in Java, multiple inheritance is not possible. It however has implementation of an interface. Compared to Java, Python has a richer built-in data structures (lists, dicts, tuples, everything is an object). Difference between Python and Jython Following are the differences 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. Standard Python code compiles to a .pyc file, while Jython program compiles to a .class file. Python extensions can be written in C language. Extensions for Jython are written in Java. Jython is truly multi-threaded in nature. Python however uses the Global Interpreter Lock (GIL) mechanism for the purpose. Both implementations have different garbage collection mechanisms. In the next chapter, we will learn how to import the Java libraries in Jython. Print Page Previous Next Advertisements ”;

Jython – Package

Jython – Package ”; Previous Next Any folder containing one or more Jython modules is recognized as a package. However, it must have a special file called __init__.py, which provides the index of functions to be used. Let us now understand, how to create and import package. Step 1 − Create a folder called package1, then create and save the following g modules in it. #fact.py def factorial(n): f = 1 for x in range(1,n+1): f = f*x return f #sum.py def add(x,y): s = x+y return s #mult.py def multiply(x,y): s = x*y return s Step 2 − In the package1 folder create and save the __init__.py file with the following content. #__init__.py from fact import factorial from sum import add from mult import multiply Step 3 − Create the following Jython script outside the package1 folder as test.py. # Import your Package. import package1 f = package1.factorial(5) print “factorial = “,f s = package1.add(10,20) print “addition = “,s m = package1.multiply(10,20) print “multiplication = “,m Step 4 − Execute test.py from Jython prompt. The following output will be obtained. factorial = 120 addition = 30 multiplication = 200 Print Page Previous Next Advertisements ”;

Jython – Home

Jython Tutorial PDF Version Quick Guide Resources Job Search Discussion Jython is the JVM implementation of the Python programming language. It is designed to run on the Java platform. Jython was created in 1997 by Jim Hugunin. It closely follows the standard Python implementation called CPython. Jython 2.7.0 was released in May 2015, which corresponds to CPython 2.7. This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules. Audience This tutorial will be helpful for Java programmers who want to utilize important features of Python i.e. Simple Syntax, Rich Data Types and Rapid Application Development in Java code. This will also be useful for Pythonistas to import feature Java class library into the Python Environment. This tutorial is made to make the programmers comfortable in getting started with Jython and its various functions. Prerequisites Since Jython helps in integrating two very popular programming technologies namely Java and Python, a reasonable knowledge of both languages is required. Print Page Previous Next Advertisements ”;

Jython – Loops

Jython – Loops ”; Previous Next In general, statements in a program are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Statements that provide such repetition capability are called looping statements. In Jython, a loop can be formed by two statements, which are − The while statement and The for statement The WHILE Loop A while loop statement in Jython is similar to that in Java. It repeatedly executes a block of statements as long as a given condition is true. The following flowchart describes the behavior of a while loop. The general syntax of the while statement is given below. while expression: statement(s) The following Jython code uses the while loop to repeatedly increment and print value of a variable until it is less than zero. Live Demo count = 0 while count<10: count = count+1 print “count = “,count print “Good Bye!” Output − The output would be as follows. count = 1 count = 2 count = 3 count = 4 count = 5 count = 6 count = 7 count = 8 count = 9 count = 10 Good Bye! The FOR Loop The FOR loop in Jython is not a counted loop as in Java. Instead, it has the ability to traverse elements in a sequence data type such as string, list or tuple. The general syntax of the FOR statement in Jython is as shown below − for iterating_var in sequence: statements(s) We can display each character in a string, as well as each item in a List or Tuple by using the FOR statement as shown below − Live Demo #each letter in string for letter in ”Python”: print ”Current Letter :”, letter Output − The output would be as follows. Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Let us consider another instance as follows. #each item in list libs = [‘PyQt’, ”WxPython”, ”Tkinter”] for lib in libs: # Second Example print ”Current library :”, lib Output − The output will be as follows. Current library : PyQt Current library : WxPython Current library : Tkinter Here is another instance to consider. #each item in tuple libs = (‘PyQt’, ”WxPython”, ”Tkinter”) for lib in libs: # Second Example print ”Current library :”, lib Output − The output of the above program is as follows. Current library : PyQt Current library : WxPython Current library : Tkinter In Jython, the for statement is also used to iterate over a list of numbers generated by range() function. The range() function takes following form − range[([start],stop,[step]) The start and step parameters are 0 and 1 by default. The last number generated is stop step. The FOR statement traverses the list formed by the range() function. For example − Live Demo for num in range(5): print num It produces the following output − 0 1 2 3 4 Print Page Previous Next Advertisements ”;

Jython – Variables and Data Types

Jython – Variables and Data Types ”; Previous Next Variables are named locations in computer’s memory. Each variable can hold one piece of data in it. Unlike Java, Python is a dynamically typed language. Hence while using Jython also; prior declaration of data type of variable is not done. Rather than the type of variable deciding which data can be stored in it, the data decides the type of variable. In the following example, a variable is assigned an integer value. Using the type() built-in function, we can verify that the type of variable is an integer. But, if the same variable is assigned a string, the type() function will string as the type of same variable. > x = 10 >>> type(x) <class ”int”> >>> x = “hello” >>> type(x) <class ”str”> This explains why Python is called a dynamically typed language. The following Python built-in data types can also be used in Jython − Number String List Tuple Dictionary Python recognizes numeric data as a number, which may be an integer, a real number with floating point or a complex number. String, List and Tuple data types are called sequences. Jython Numbers In Python, any signed integer is said to be of type ‘int’. To express a long integer, letter ‘L’ is attached to it. A number with a decimal point separating the integer part from a fractional component is called ‘float’. The fractional part may contain an exponent expressed in the scientific notation using ‘E’ or ‘e’. A Complex number is also defined as numeric data type in Python. A complex number contains a real part (a floating-point number) and an imaginary part having ‘j’ attached to it. In order to express a number in the Octal or the Hexadecimal representation, 0O or 0X is prefixed to it. The following code block gives examples of different representations of numbers in Python. int -> 10, 100, -786, 80 long -> 51924361L, -0112L, 47329487234L float -> 15.2, -21.9, 32.3+e18, -3.25E+101 complex -> 3.14j, 45.j, 3e+26J, 9.322e-36j Jython Strings A string is any sequence of characters enclosed in single (e.g. ‘hello’), double (e.g. “hello”) or triple (e.g. ‘“hello’” o “““hello”””) quotation marks. Triple quotes are especially useful if content of the string spans over multiple lines. The Escape sequence characters can be included verbatim in triple quoted string. The following examples show different ways to declare a string in Python. str = ’hello how are you?’ str = ”Hello how are you?” str = “””this is a long string that is made up of several lines and non-printable characters such as TAB ( t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ n ], or just a NEWLINE within the variable assignment will also show up. “”” The third string when printed, will give the following output. this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up. Jython Lists A List is a sequence data type. It is a collection of comma-separated items, not necessarily of the same type, stored in square brackets. Individual item from the List can be accessed using the zero based index. The following code block summarizes the usage of a List in Python. list1 = [”physics”, ”chemistry”, 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print “list1[0]: “, list1[0] print “list2[1:5]: “, list2[1:5] The following table describes some of the most common Jython Expressions related to Jython Lists. Jython Expression Description len(List) Length List[2]=10 Updation Del List[1] Deletion List.append(20) Append List.insert(1,15) Insertion List.sort() Sorting Jython Tuples A tuple is an immutable collection of comma-separated data items stored in parentheses. It is not possible to delete or modify an element in tuple, nor is it possible to add an element to the tuple collection. The following code block shows Tuple operations. tup1 = (”physics”,”chemistry‘,1997,2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print “tup1[0]: “, tup1[0] print “tup2[1:5]: “, tup2[1:5] Jython Dictionary The Jython Dictionary is similar to Map class in Java Collection framework. It is a collection of key-value pairs. Pairs separated by comma are enclosed in curly brackets. A Dictionary object does not follow zero based index to retrieve element inside it as they are stored by hashing technique. The same key cannot appear more than once in a dictionary object. However, more than one key can have same associated values. Different functions available with Dictionary object are explained below − dict = {”011”:”New Delhi”,”022”:”Mumbai”,”033”:”Kolkata”} print “dict[‘011’]: “,dict[”011”] print “dict[”Age”]: “, dict[”Age”] The following table describes some of the most common Jython Expressions related to Dictionary. Jython Expression Description dict.get(‘011’) Search len(dict) Length dict[‘044’] = ‘Chennai’ Append del dict[‘022’] Delete dict.keys() list of keys dict.values() List of values dict.clear() Removes all elements Print Page Previous Next Advertisements ”;

Jython – Using Java Collection Types

Jython – Using Java Collection Types ”; Previous Next In addition to Python’s built-in data types, Jython has the benefit of using Java collection classes by importing the java.util package. The following code describes the classes given below − Java ArrayList object with add() remove() get() and set() methods of the ArrayList class. Live Demo import java.util.ArrayList as ArrayList arr = ArrayList() arr.add(10) arr.add(20) print “ArrayList:”,arr arr.remove(10) #remove 10 from arraylist arr.add(0,5) #add 5 at 0th index print “ArrayList:”,arr print “element at index 1:”,arr.get(1) #retrieve item at index 1 arr.set(0,100) #set item at 0th index to 100 print “ArrayList:”,arr The above Jython script produces the following output − C:jython27bin>jython arrlist.py ArrayList: [10, 20] ArrayList: [5, 20] element at index 1: 20 ArrayList: [100, 20] Jarray Class Jython also implements the Jarray Object, which allows construction of a Java array in Python. In order to work with a jarray, simply define a sequence type in Jython and pass it to the jarrayobject along with the type of object contained within the sequence. All values within a jarray must be of the same type. The following table shows the character typecodes used with a jarray. Character Typecode Corresponding Java Type Z Boolean C char B byte H short I int L long F float D double The following example shows construction of jarray. Live Demo my_seq = (1,2,3,4,5) from jarray import array arr1 = array(my_seq,”i”) print arr1 myStr = “Hello Jython” arr2 = array(myStr,”c”) print arr2 Here my_seq is defined as a tuple of integers. It is converted to Jarray arr1. The second example shows that Jarray arr2 is constructed from mySttr string sequence. The output of the above script jarray.py is as follows − array(”i”, [1, 2, 3, 4, 5]) array(”c”, ”Hello Jython”) Print Page Previous Next Advertisements ”;