Ant Jython Task
Wednesday, August 20th, 2008MyArch Jython task has a number of advantages over built-in <script language="jython">
way of invoking Jython from Ant.
Specifically, the task provides the following benefits:
- More graceful exception handling. Jython code invoked using "script" could generate long error stack that includes the Java stack trace of the "script" task. This is especially painful if you invoke other Ant tasks from Jython (you can do it using MyArch PAnt utility) that add their own Java stack trace. MyArch Jython task produces a brief readable error stack. I personally think that unwieldy error traces is a big issue in the industry and it's far from innocuous.
- You can use Ant properties as parameters (the task makes them available in the local namespace of the calling script).
- Ant "project" object is passed in the global variable "antProject" (available from the built-in namespace). In other words, "antProject" is available to all modules/functions invoked using "jython".
- Convenience "import" attribute.
- There is also a JythonPath task for easily setting jython path from Ant path.
- Jython interpreter is initialized once per Ant project. All scripts invoked from the same Ant project reuse the same built-in namespace. So you can define variables and imports in one call and use them in a subsequent call.
- Task name ( the name that prefixes all console output from Ant for a given task) is generated automatically based on the supplied Python code.
Example:
Ant code:
<jythonPath pythonPathRef="python.path" />
<property name="testProp" value="testVal" />
<jython>
print "Property from ant:", testProp
# define a var that we can use in other scripts
s="test"
</jython>
<jython>
print "Var created earlier: ",s
</jython>
<jython import="from testmodule import *" exec="test(testProp)" />
"testmodule" python code:
def test (prop):
print "Passed parameter: ",prop
print "Test property: ",antProject.properties["testProp"]
Jython task attributes:
- exec - python code to execute. This has to be a single line, e.g.,
mod.fun()although you could combine multiple statements separated by ";". - import - a convenience attribute for providing "import" statement. Its only purpose is to make the task invocation more readable. Alternatively, you can have "import" as part of the"exec",e.g.,
exec="import mod;mod.fun()". - execfile - execute a python script. This has to be an absolute path to a python file.
JythonPath task attributes:
- pythonPath - python.path to use.
- pythonPathRef - the python.path to use, given as reference to a PATH defined elsewhere.
Jython task is part of myarch-antutil project. Download jython task.
You may also be interested in PAnt - Ant python wrapper.