Monday, September 4, 2017

EXECUTING PYTHON SNIPPET FROM JAVA 

When i was researching on ways to call or execute python snippet in java landed up in three ways one is conventional way of doing it using old run time classes to call it , The next one is using Process builder classes to call it and the last one is using the Jython (serves as a python interpreter) which is written in java. 

In this current post i will be posting few snippets how to do it through process builder classes.

When the python program does not have any command line arguments

Code Snippet: 


package com.connectors.python;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestRuntimeConnector {
      
  public static void getOutputAsString(Process processInstance){
         String stringInstance = null;
         try {
         BufferedReader stdInput = new BufferedReader(new InputStreamReader
                       (processInstance.getInputStream()));
      BufferedReader stdError = new BufferedReader(new InputStreamReader
                (processInstance.getErrorStream()));
      while ((stringInstance = stdInput.readLine()) != null) {
        System.out.println(stringInstance);
      }
      System.out.println("Here is the standard error of the command (if any):\n");
      while ((stringInstance = stdError.readLine()) != null) {
        System.out.println(stringInstance);
      }
      System.exit(0);
    }catch (IOException e) {
      System.out.println("exception happened - here's what I know: ");
      e.printStackTrace();
      System.exit(-1);
    }
  }

  public static void main(String args[]) {
    try {
     long startTime = System.nanoTime();
     Process processInstance = Runtime.getRuntime().exec
                (new String[]{"python","sample.py"});
     long endTime = System.nanoTime();
     long duration = (endTime - startTime)/1000000;
     System.out.println("The Time taken to execute the method is "+duration+"milli seconds");
        getOutputAsString(processInstance);
       } catch (IOException exception) {
         exception.printStackTrace();
       }
  }
}

When the python program has command line arguments and you need to pass the command line arguments in method mentioned in the below snippet.

Process randomNumberInstance = Runtime.getRuntime().exec
     (new String[]{"python","randomNumber.py","10"});

Moreover if you need to pass multiple arguments, pass one by one separate it by comma.

No comments:

Post a Comment