Friday, 9 December 2016

Java Embedded Python (JEP)


Prerequisite:
  1. JDK 6+
  2. Python 2.6+

Installation:
  1. sudo pip install jep

How to run JEP Shell?
The jep run script is available at /usr/local/bin directory. You can go to terminal and type “jep” to launch JEP shell.

How to Setup and Run python script in java using JEP?
  1. Setting up Environment Variable
    1. LD_PRELOAD="/usr/lib/x86_64-linux-gnu/libpython2.7.so"
    2. LD_LIBRARY_PATH="/usr/lib:/usr/local/lib/python2.7/dist-packages/"
Note: if you are not sure of the values you should set for this environment line variables, open the file “/usr/local/bin/jep” and check the values for same.
  1. add jar file => “/usr/local/lib/python2.7/dist-packages/jep/jep-3.5.0.jar” into your classpath or buildpath.
  2. Instantiate “Jep” class and use it to execute python code.

Example 1:

Main.java:

import jep.Jep;
import jep.JepException;
public class Main {
   public static void main(String[] args) throws JepException {
   Jep jep = new Jep();
   jep.eval("import sys");
   jep.eval("s = 'Hello World'");
   jep.eval("print s");
   String java_string = jep.getValue("s").toString();
   System.out.println("Java String:" + java_string);
   jep.runScript("src/myscript.py");
   }
}

myscript.py:

for i in range(1,5):
print i



No comments:

Post a Comment