How to execute python scripts in maven projects


This post would demo how to execute python scripts in maven projects. We would execute a python script in the build process and generate a file to be packaged in the target jar.


  • Maven 3.x
  • Python 2.7

The exec-maven-plugin plugin

The exec-maven-plugin let you execute scripts during maven build lifecycle. There are two goals of this plugin:

  • exec:exec execute programs and Java programs in a separate process.
  • exec:java execute Java programs in the same VM.

We would use the exec:exec goal to execute python script

The pom.xml


The explanation:

  • We add a build plugin named exec-maven-plugin to the maven project
  • The plugin has a configuration to run python script named in the src/main/resources directory
  • The plugin would be executed at the generate-resources lifecycle of the maven build process

The maven generate-resources lifecycle in short:

generate-sources generate any source code for inclusion in compilation.

The python script

Create a new python script named in the src/main/resources directory of the project, the content is:

# coding=UTF-8
import os,io
cur_path = os.getcwd() #should be the src/main/resources
with"/tempfile", mode='w') as the_file:
    the_file.write(u'hello maven')

The script do the followings:

  • get the current path, it should be src/main/resources
  • we use function to create a new file named tempfile
  • we write hello maven string into the file

run the script

mvn compile

we got this:

[INFO] Building test-maven-python 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] --- exec-maven-plugin:1.6.0:exec (python-build) @ test-maven-python ---
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ test-maven-python ---
[debug] execute contextualize

check the file and content:

➜  resources git:(master) ✗ ll tempfile 
-rw-r--r--  1 zzz  staff    11B Apr 28 22:19 tempfile
➜  resources git:(master) ✗ cat tempfile 
hello maven%      


The exec-maven-plugin let you execute java/system scripts in the maven build lifecycle, and in this demo, we see that we can execute any python script in the maven project.

You can find detail documents about the git and remote here: