JYTHON is a Java implementation of Interpretive language PYTHON. The JDK support running JYTHON scritps in Java. But JSR-233 is required to run the scritps.
1. JDK version >= 1.5
2. Download JSR 233 from https://scripting.dev.java.net/ and put the jython-engine.jar and jython.jar file to jre bin folder.
3. create a file sample.py
from java.lang import Object
from java.lang import System
print 'How are u doing, Simple py interpretation from java. direct code change'
def hello():
print 'Hello dude'
4. create a RunScriptFileDemo.java file
package com.jana.san;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class RunScriptFileDemo {
public static void main(String[] args) {
File scripts = new File("scripts");
// create ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jython");
// open file, and execute the script
try {
Reader reader = new FileReader(new File(scripts,"sample.py"));
engine.eval(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. compile and execute the class
0 comments:
Post a Comment