-
Notifications
You must be signed in to change notification settings - Fork 8
Easy Python Scripting in Java Plugins
This tutorial is determined for developers who want to use some Python scripts or even libraries in their Jenkins plugin (written in Java). It's really easy, you just have to follow these steps:
-
Mark the python-wrapper plugin dependency in your plugin's pom.xml:
<dependencies> ... <dependency> <groupId>org.jenkins-ci.plugins</groupId> <artifactId>python-wrapper</artifactId> <version>1.0.3</version> </dependency> ... </dependencies>
-
Mark all .py files as resource files in your plugin's pom.xml:
<build> <resources> ... <resource> <directory>src/main</directory> <includes> <include>**/*.py</include> </includes> </resource> ... </resources> </build>
-
Don't forget to determine all other resource directories which you are using (like resources or webapp):
<build> <resources> ... <resource> <directory>src/main/resources</directory> <filtering>false</filtering> </resource> ... </resources> </build>
-
Add your Python files to the src/main/python directory. All scripts should be compatible with the Jython 2.5.3.
-
Init and use a PythonExecutor object in your Java class:
... import jenkins.python.DataConvertor; import jenkins.python.PythonExecutor; ... class MyClass { private transient PythonExecutor pexec; ... public MyClass() { pexec = new PythonExecutor(this); } ... private void someMethod() { // call some_function("some example", 12) in my_class.py file and return a result boolean result = pexec.execPythonBool("some_function", "some example", DataConvertor.fromInt(12)); } ... }
See other PythonExecutor.exec*() and DataConvertor.from*() methods for all possibilities.
-
Add a Python script to the src/main/python directory, which has the same name as your Java class, but in the Python file name convention. For the previous example it's my_class.py. You can also import and use another modules including all Jenkins packages and classes:
... # file src/main/python/my_class.py ... import re import mymodule import hudson.Util as Util ... def some_function(text, length): if len(text) == length: return True else: return False ...
-
Test the plugin with
$ mvn hpi:run. -
Done.