Using wsadmin scripting with Jython
Jython is an alternate implementation of Python, and is written entirely in Java™.
The wsadmin tool uses Jython V2.7. The following information is a basic summary of Jython syntax.
In all sample code, the
=> notation at the beginning of a line represents
command or function output.
For additional Jython V2.7 specific information, see Jython V2.7 behavior changes
If Jython V2.1 is required, then you must explicitly configure it using one of the following methods:
- Specify Jython V2.1 using the wsadmin
wsadmin -conntype soap -usejython21 true -f test.py
- Specify Jython V2.1 using a custom property in the wsadmin.properties file:
The default value is false.
The function is either the name of a built-in function or a Jython function. For example, the following functions return "Hello, World!" as the output:
print "Hello, World!" =>Hello, World! import sys sys.stdout.write("Hello World!\n") =>Hello, World!
In the example,
a built-in module of the Python language. In the Python language, modules are name spaces which are
places where names are created. Names that reside in modules are called attributes. Modules
correspond to files and the Python language creates a module object to contain all the names defined
in the file. In other words, modules are name spaces.
MBeanoperation, and the
MBeanmethod returns a string that includes some NLS translated characters such as the French accent character, Jython automatically converts the string to a python unicode string, and returns the converted string to wsadmin. If you include the Jython print output command in the script that invokes the
MBeanmethod, the NLS translated characters are included in the string that the
MBeanmethod returns to wsadmin instead of the python unicode values. To avoid the displaying of NLS translated characters, use a variable for the
MBeanreturn (for example,
output = AdminControl.invoke(mbean)) and then use print output. Use the Jython print command to convert strings that contain NLS translated characters correctly.
output = AdminControl.invoke(mbean)) and then use
print output. Use the Jython
To assign objects to names, the target of an assignment goes on the first side of an equal sign (=) and the object that you are assigning on the other side. The target on the first side can be a name or object component, and the object on the other side can be an arbitrary expression that computes an object. The following rules exist for assigning objects to names:
- Assignments create object references.
- Names are created when you assign them.
- You must assign a name prior to referencing it.
Variable name rules are like the rules for the C language; for example, variable names can have an underscore character (_) or a letter plus any number of letters, digits, or underscores.
a = 5 print a => 5 b = a print b => 5 text1, text2, text3, text4 = 'good', 'bad', 'pretty', 'ugly' print text3 => pretty
The second example assigns the value of variable a to variable b.
Types and operators
The following list contains examples of the built-in object types:
- Numbers. For
8, 3.133, 999L, 3+4j num1 = int(10) print num1 => 10
- Strings. For
'name', "name's", '' print str(12345) => '12345'
- Lists. For
x = [1, [2, 'free'], 5] y = [0, 1, 2, 3] y.append(5) print y => [0, 1, 2, 3, 5] y.reverse() print y => [5, 3, 2, 1, 0] y.sort() print y => [0, 1, 2, 3, 5] print list("apple") => ['a', 'p', 'p', 'l', 'e'] print list((1,2,3,4,5)) => [1, 2, 3, 4, 5] test = "This is a test" test.index("test") => 10 test.index('s') => 3
The following list contains examples of the operators:
- x or y
y is evaluated only if x is false. For example:
print 0 or 1 => 1
- x and y
y is evaluated only if x is true. For example:
print 0 and 1 => 0
- x + y , x - y
Addition and concatenation, subtraction. For example:
print 6 + 7 => 13 text1 = 'Something' text2 = ' else' print text1 + text2 => Something else list1 = [0, 1, 2, 3] list2 = [4, 5, 6, 7] print list1 + list2 => [0, 1, 2, 3, 4, 5, 6, 7] print 10 - 5 => 5
- x * y, x / y, x % y
Multiplication and repetition, division, remainder and format. For example:
print 5 * 6 => 30 print 'test' * 3 => test test test print 30 / 6 => 5 print 32 % 6 => 2
- x[i], x[i:j], x(...)
Indexing, slicing, function calls. For example:
test = "This is a test" print test => s print test[3:10] => s is a print test[5:] => is a test print test[:-4] => This is a print len(test) => 14
- <, <=, >, >=, ==, <>, !=, is is not
Comparison operators, identity tests. For example:
L1 = [1, ('a', 3)] L2 = [1, ('a', 2)] L1 < L2, L1 == L2, L1 > L2, L1 <> L2, L1 != L2, L1 is L2, L1 is not L2 => (0, 0, 1, 1, 1, 0, 1)
If a statement must span multiple lines, you can also add a back slash (\) at the end of the previous line to indicate you are continuing on the next line. Do not use blank space characters, specifically tabs or spaces, following the back slash character. For example:
text = "This is a test of a long lines" \ " continuing lines here." print text => This is a test of a long lines continuing lines here.
Functions and scope
defstatement to define functions. Functions related statements include:
defstatement creates a function
objectand assigns it to a name. The
returnstatement sends a result object back to the caller. This is optional, and if it is not present, a function exits so that control flow falls off the function body.
globalstatement declares module-level variables that are to be assigned. By default, all names assigned in a function are local to that function and exist only while the function runs. To assign a name in the enclosing module, list functions in a global statement.
The basic syntax to define a function is the following:
def name (arg1, arg2, ... ArgN) statements return value
where name is the name of the function being defined. It is followed by an open parenthesis, a close parenthesis, and a colon. The arguments inside parenthesis include a list of parameters to the procedures. The next line following the colon is the body of the function. A group of commands that form the body of the function. Once you define a Jython function, it is used just like any of the built-in functions. For example:
def intersect(seq1, seq2): res =  try: for x in seq1: if x in seq2: res.append(x) except: pass return res
To call this function, use the following command:
s1 = "SPAM" s2 = "SCAM" intersect(s1, s2) => [S, A, M] intersect([1,2,3], (1.4)) => 
Make comments in the Jython language with the pound character (#).
The Jython shells pass the command-line arguments to the script as the value of the sys.argv. In wsadmin Jython, the name of the program, or script, is not part of sys.argv. Unlike wsadmin Jython, Jython stand-alone takes the script file as the initial argument to the script. Since sys.argv is an array, use the index command to extract items from the argument list. For example, test.py takes three arguments a, b, and c.
wsadmin -f test.py a b c
import sys first = sys.argv second = sys.argv third = sys.argv arglen = len(sys.argv)
There are two looping statements:
conditional statement is
if. The error handling statement is
Finally, there are some statements to fine-tune control flow:
ifstatement selects actions to perform. The
ifstatement might contain other statements, including other
ifstatement can be followed by one or more optional
elifstatements and ends with an optional
The general format of an if looks like the following:
if test1 statements1 elif test2 statements2 else statements3
weather = 'sunny' if weather == 'sunny': print "Nice weather" elif weather == 'raining': print "Bad weather" else: print "Uncertain, don't plan anything"
whilestatement consists of a header line with a test expression, a body of one or more indented statements, and an optional
elsestatement that runs if control exits the loop without running into a break statement. The
whilestatement repeatedly runs a block of indented statements as long as a test in the header line keeps evaluating a true value. An example of
while test1 statements1 else statements2
a = 0; b = 10 while a < b: print a a = a + 1
forstatement begins with a header line that specifies an assignment target or targets, along with an object you want to step through. The header is followed by a block of indented statements which you want to repeat.
An example of a
for target in object: statements else: statements
It assigns items in the sequence object to the target, one by one, and runs the loop body for each. The loop body typically uses the assignment target to refer to the current item in the sequence as if it were a cursor stepping through the sequence. For example:
sum = 0 for x in [1, 2, 3, 4]: sum = sum + x
- break, continue, and pass
You can control loops with the
breakstatement jumps out of the closest enclosing loop (past the entire loop statement). The
continuestatements jumps to the beginning of the closest enclosing loop (to the header line of the loop), and the
passstatement is an empty statement placeholder.
A statement will raise an error if it is called with the wrong number of arguments, or if it detects some error condition particular to its implementation. An uncaught error stops the running of a script. The
trystatement is used to trap such errors. Python
trystatements come in two flavors, one that handles exceptions and one that runs finalization code whether exceptions occur or not. The
elsestatement starts with a try header line followed by a block of indented statements, then one or more optional except clauses that name exceptions to be caught, and an optional
elseclause at the end. The
finallystatements starts with a try header line followed by a block of indented statements, then the finally clause that always runs on the way out whether an exception occurred while the try block was running or not.
An example of
try: statements except name: statements except name, data: statements else statements
try: myfunction() except: import sys print 'uncaught exception', sys.exc_info() try: myfilereader() except EOFError: break else: process next line here
The general format of a try and finally looks like the following:
try statements finally statements
def divide(x, y): return x / y def tester(y): try: print divide(8, y) finally: print 'on the way out...'
- Statements run sequentially by default. Statements normally end at the end of the line on which they appear. When statements are too long to fit on a single line you can also add a backslash (\) at the end of the prior line to indicate you are continuing on the next line.
- Block and statement boundaries are detected automatically. There are no braces, or begin or end delimiter, around blocks of code. Instead, the Python language uses the indentation of statements under a header in order to group the statements in a nested block. Block boundaries are detected by line indentation. All statements indented the same distance belong to the same block of code until that block is ended by a line less indented.
- Compound statements = header; ':', indented statements. All compound statements in the Python language follow the same pattern: a header line terminated with a colon, followed by one or more nested statements indented under the header. The indented statements are called a block.
- Spaces and comments are usually ignored. Spaces inside statements and expressions are almost always ignored (except in string constants and indentation), so are comments.
Calling scripts using another script
Use the execfile command to call a Jython script from another Jython script. For example:
Create a script called test1.py that contains the following:
execfile('c:/temp/script/testFunctions.py') print printName('Cathy', 'Smith')
Create a script called testFunctions.py that contains the following:
def printName(first, last): name = first + ' ' + last return name
Then pass the following path as a script argument:
wsadmin -lang jython -f 'c:/temp/script/test1.py'
You must use forward slashes (/) as your path separator. Backward slashes (\) do not work.
Running Jython scripts that use packages
If you run scripts that use packages, you must provide the wsadmin tool with the search path for the Jython scripts that use packages.
To provide this information to the wsadmin tool, include the following option when you start the tool:
where dir1 and dir2 represent the directory search paths for libraries containing the Jython packages.
Jython usage with Microsoft Windows directories
Jython treats the following list of characters or conditions as special. Do not use the characters, if possible, when using Jython.
- a backslash followed by a sequence of numbers between 0 and 7
When specifying Microsoft Windows file paths in Jython you must be aware of these special conditions. When you must use any of these character strings, you can counteract the Jython interpretation of these special character strings by using either "two backslashes" instead of one backslash or by substituting a forward slash for the single backslash. The following examples illustrate how to make these adjustments.
|Erroneous Path||Corrected Double Backslash Path||Corrected Forward Slash Path|