Issue
I'm trying to run Python Scripts in my Java Application with Jyton/ScriptEngine but it's not working. ScriptEngine does not find JythonScriptEngine.
public static void main(String[] Args) throws FileNotFoundException, ScriptException {
PySystemState engineSys = new PySystemState();
engineSys.path.append(Py.newString("C:/Users/User/AppData/Local/jython2.7.2/jython.jar"));
Py.setSystemState(engineSys);
StringWriter writer = new StringWriter();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("C:/*/MyScript.py"), context);
System.out.println(engine.get("value"));}
I added Jython into my Project Libary.
But it didnt work.
I hope somebody can help me. Thank you in advance. :D
Solution
I have not worked with Jython library but its seems that it helps to get python libraries/interpreter in java code. Your code looks like you want to execute some python class and get result in Java. You can simply execute it as a shell command and get its result like following utility function:
public static String runSystemCommand(String fileToRun) throws IOException
{
Process p = Runtime.getRuntime().exec(fileToRun);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String result = input.lines().collect(Collectors.joining("\n"));
input.close();
return result;
}
public static void main(String[] args) throws Exception
{
System.out.println(runSystemCommand("python /home/saad/shell.py"));
}
Answered By - saadeez
Answer Checked By - Marilyn (JavaFixing Volunteer)