Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Intro to Jython, Part 1: Java programming made easier

Barry Feigenbaum, Sr. Consulting IT Architect, IBM

Dr. Barry Feigenbaum is a member of the IBM Worldwide Accessibility Center, where he is part of team that helps IBM make its own products accessible to people with disabilities. Dr. Feigenbaum has published several books and articles, holds several patents, and has spoken at industry conferences such as JavaOne. He serves as an Adjunct Assistant Professor of Computer Science at the University of Texas, Austin.

Dr. Feigenbaum has more than 10 years of experience using object-oriented languages like C++, Smalltalk, the Java programming language, and Jython. He uses the Java language and Jython frequently in his work. Dr. Feigenbaum is a Sun Certified Java Programmer, Developer, and Architect.


Acknowledgements

I would like to acknowledge Mike Squillace and Roy Feigel for their excellent technical reviews of this tutorial.

Summary:  This is the first in a two-part tutorial that will introduce you to the Jython scripting language and provide you with enough knowledge to begin developing your own Jython-based applications. In this first half of the tutorial, you'll learn the concepts and programming basics of working with Jython, including access options and file compilation, syntax and data types, program structure, procedural statements, and functions.

Date:  08 Apr 2004
Level:  Introductory PDF:  A4 and Letter (1165 KB | 65 pages)Get Adobe® Reader®

Activity:  88598 views
Comments:  

Modules and importing

About modules and imports

Jython breaks programs down into separate files, called modules. Modules are reused by importing them into your code. Jython provides many modules for you to reuse (see Appendix F: Jython library summary). Jython also allows you to reuse any Java class and API.

Modules and packages

A module is an executable Jython file that contains definitions (for variables, functions and/or classes). Modules are imported (executed and bound) into other programs/scripts or modules. It is necessary to import a module when the importing program or module needs to use some or all of the definitions in the imported module.

Jython packages are conceptually hierarchically structured sets of modules. They are implemented as directories that contain one or more modules and a special file, __init__.py, that is executed before the first module of the package is executed.

Modules and packages enable reuse of the extensive standard Jython and Java libraries. You can also create modules and packages for reuse in you own Jython applications. For more information on the available Jython modules see Appendix F: Jython library summary. For more information on the available Java libraries visit the Sun Microsystems' Java technology home page (in Resources).

The import statement

The import statement executes another file and adds some or all of the names bound in it to the current namespace (see Visibility and scopes). The current namespace will generally be the global namespace in the importing file. All statements, including assignments, in the module are executed. The import statement comes in several forms:

import module {as alias}

   -- or --

from module import name {as alias}

   -- or --

from module import *

The module value names a Jython (.py) file or dotted-path to a Jython package. The name value selects specific names from the module. Module names are case sensitive. These arguments can be repeated. The optional alias value allows imported objects to be renamed.


Example imports

Below are some example import statements:

Example Comment(s)
import sys Import the sys module. All names in sys can be referenced by the prefix sys.
from sys import exc_info Imports the exc_info function from the sys module. No prefix is needed.
from sys import * Imports all the names and functions in the sys module. No prefix is needed.
from sys import exc_info as einfo Imports the exc_info function from the sys module and names it einfo. No prefix is needed.
from string import uppercase as uc, lowercase as lc Imports the uppercase and lowercase functions from module string. No prefix is needed.
import sys, string Imports modules sys and string
import com.ibm.tools.compiler as compiler Imports the compiler module from the com.ibm.tools package giving it the short name compiler.

Importing modules and packages

To import a module or package, Jython must be able to find the associated source (.py) file. Jython uses the python.path (very similar to the Java language's CLASSPATH) and python.prepath variables in the Jython registry to search for these files. You can use any text editor to add to or update the registry file in the Jython home directory (usually c:\jython-2.1). For more information, see the Jython registry (in Resources) or the registry file itself.

By default, Jython will search the directory containing the executing source file; thus, modules located in the same directory as the importing Jython program can be found. Frequently the current directory is also on the path. Simply enter the following command to examine the current search paths:

import sys
print sys.path

On my machine, when running in the C:\Articles directory, the above command produces the following output:

['', 'C:\\Articles\\.', 'C:\\jython-2.1\\Lib', 'C:\\jython-2.1']

To find Java class files, Jython searches both the Java CLASSPATH and the sys.path values.


Import is executable

Unlike in the Java language, the import statement is executable and is not a compiler directive in Jython. Thus, imports do not need to be done at the start of a module; just sometime before the imported symbols are used. In fact importing can be done conditionally, as in the following example.

   :
# lots of other stuff
   :
if __name__ == "__main__":
     :
     from sys import exit
     exit(0)
           

Imports can also be undone, as shown here:


import sys
   :
# lots of other stuff
   :
del sys


Subsetting imports

When you import modules, all values assigned or functions created in the module are usually available for reference by the module importer. You can prevent this by altering the code within the module. Either start the name with an underscore (_) or define a special variable, __all__, at the start of the module, listing only the names of the variables or functions you want to be imported. For example, the __all__ definition below:

__all__ = ["getline","clearcache","checkcache"]

would only import the names getline, clearcache, and checkcache.

A similar strategy can be used at the module directory level. Defining the variable __all__ in a file called __init__.py instructs the interpreter as to which modules to import from the package if the wildcard (*) is used in the import statement. For instance, if the line __all__ = ['mod1', 'mod3', 'globals'] is in a file called __init__.py in a directory named modules, it will cause the statement from modules import * to import the modules mod1, mod3, and globals from the modules directory.


Running native applications

Using the os.system function, Jython can also run any external program that can be found on the current host PATH, such as a host operating system application. For example, to compile a Java program you could use

import os
import sys

cmd = "javac %(name)s.java 1>%(name)s.out 2>%(name)s.err" % \
                 {'name': sys.argv[1]})
rc = os.system(cmd)
if rc == 0:
     print "Successful"
else:
     print "Failed: return code=%i..." % rc
     # read and process the .err file...


8 of 16 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=131933
TutorialTitle=Intro to Jython, Part 1: Java programming made easier
publish-date=04082004
author1-email=feigenba@us.ibm.com
author1-email-cc=jaloi@us.ibm.com