How do I run Python Scripts in Java with the ScriptEngine?

Question:

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. 😀

Asked By: Skyliam

||

Answers:

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

I found a workaround using the ProcessBuilder. Its running my python script in the shell like @saadeez showed me.

@Test
  public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
  ProcessBuilder processBuilder = new ProcessBuilder("python", "C:.py");
  processBuilder.redirectErrorStream(true);

  Process process = processBuilder.start();
  List<String> results = readProcessOutput(process.getInputStream());
  System.out.println(results);
  int exitCode = process.waitFor();
  assertEquals("0", ""+exitCode);}


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;}
Answered By: Skyliam